javascript/study
[json] 코드를 api로 전달하기
moondinsk
2024. 9. 22. 20:07
드림코딩 10강
Json - savascript object notation (Javascript object와 관련된 파일 , data format)
{ key : value }
사용처 - 브라우저, 모바일, 파일
// 1. Object -> JSON
// stringify(obj)
let json = JSON.stringify(true); // true
let fruits = JSON.stringify(['apple', 'banana']); // ["apple","banana"]
let rabbit = {
name : "tory",
color : "white",
birthDate : new Date(), // "2024-09-22 T13:33:12.663"
symbol : Symbol(id), // 변환되지 않음
jump : () => { // 변환되지 않음
console.log(`${name} can jump!`); // 말그대로 stringify!
},
}
json = JSON.stringify(rabbit);
console.log(json);
// 원하는 프로퍼티를 불러와서 목록을 만들기
json = JSON.stringify(rabbit, ["name", "color"]);
console.log(json) // {"name":"tory", "color":"white"}
json = JSON.stringify(rabbit, (key, value) => {
console.log(`key: ${key}, value: ${value}`);
// return value; // 모든 key와 value 전달
return key === "name" ? "ellie" : value; //콜백함수를 통해 세밀하게 통제가 가능하다
});
// 2. JSON -> Object
// parse(json)
json = JSON.stringify(rabbit);
const obj = JSON.parse(json);
console.log(obj);
const obj = JSON.parse(json, (key, value) => {
console.log(`key: ${key}, value: ${value}`);
return key === 'birthDate'? new Date(value) : value;
});
console.log(obj);
rabbit.jump(); // can jump!
obj.jump(); // Uncaught TypeError: obj.jump is not a function
// 함수는 변환된 적이 없으므로 불러올수도 없다
rabbit.birthDate.getDate(); // 29
obj.birthDate.getDate(); // string "2024-09-22 T13:33:12.663" 이기때문에 날짜를 가져올수없음
// 29
오버로딩 :함수이름은 동일하지만 파라미터를 몇개 불러오느냐에 따라 다른 함수를 불러옴
옵셔널 함수
?: 있으나 없으나 상관없음
stringify -> string 으로 만들어줌