let json = JSON.stringify(true); //boolean 값
console.log('json:', json); //json: true
//함수이름은 동일하지만 몇 개의 parameter를 전달하느냐에 따라 달라지는게 overloading
json = JSON.stringify(['apple', 'banana']); //배열
console.log(json); //["apple", "banana"] 더블 쿼트에 들어감
const rabbit = {
name: 'tori',
color: 'white',
size: null,
birthDate: new Date(),
jump: () => {
console.log(`${this.name} can jump`);
}
};
json = JSON.stringify(rabbit); //객체
console.log(json);
//{"name":"tori","color":"white","size":null,"birthDate":"2021-01-01T10:28:13.636Z"} 함수는 포함 X
json = JSON.stringify(rabbit, ["name"]);
console.log(json); //{"name":"tori"}
json = JSON.stringify(rabbit, (key, value) => {
console.log(`key: ${key}, value: ${value}`);
return key === 'name' ? 'emma' : value;
//key가 name이라면 emma로 출력하기
});
console.log(json); //모든 key과 value가 출력된 후 마지막 출력에 이름이 바뀌어 출력
json = JSON.stringify(rabbit);
const obj = JSON.parse(json, (key, value) => {
console.log(`key: ${key}, value: ${value}`);
return key === 'birthDate' ? new Date(value) : value;
});
console.log(obj);
//{name: "tori", color: "white", size: null, birthDate: "2021-01-01T10:36:24.883Z"}
rabbit.jump(); //can jump
//rabbit이라는 obj에는 jump라는 함수가 있었지만 string화 된 json을 다시 obj로 만들 때는 함수가 포함되어 있지 않음
//obj.jump(); 는 오류
console.log(rabbit.birthDate.getDate());
console.log(obj.birthDate.getDate()); //Date라는 API를 사용했기 때문에 obj를 받아올 때 콜백함수를 이용해 세밀하게 받아올 것
참고 사이트
JSON Diff Checker(디버깅)
JSON Beautifier/editor
JSON Parser : json타입을 object로 어떻게 표기되는지 확인하고 싶을 때
JSON Validator : JSON이 이상할 때 확인