텍스트 테이터 포맷
객체를 ---> Json 포맷의 문자열로 변환
클라이언트가 서버
로 객체를 전송하려면 (문자열화 필요) 이 때 사용
const obj = {
name: "WI",
age: 100,
alive: true,
hobby: ["programming", "music"],
};
// 객체 -> JSON (serializing)
const json = JSON.stringify(obj);
console.log(json);
// {"name":"WI","age":100,"alive":true,"hobby":["programming","music"]}
const prettyJSON = JSON.stringify(obj, null, 2);
console.log(typeof prettyJSON, prettyJSON);
// string {
// "name": "WI",
// "age": 100,
// "alive": true,
// "hobby": [
// "programming",
// "music"
// ]
// }
// JSON.stringify(obj, replacer, space) 에서 replacer 메서드 정의
function filter(key, value) {
// undefined 는 반환 X
return typeof value === "number" ? undefined : value;
}
const strFilteredJSON = JSON.stringify(obj, filter, 2);
console.log(typeof strFilteredJSON, strFilteredJSON);
// string {
// "name": "WI",
// "alive": true,
// "hobby": [
// "programming",
// "music"
// ]
// }
const obj = {
name: "WI",
age: 100,
alive: true,
hobby: ["programming", "music"],
};
// 객체 -> JSON (serializing)
const json = JSON.stringify(obj);
// JSON -> 객체 (deserializing)
const parsed = JSON.parse(json);
console.log(typeof parsed, parsed);
// object {
// name: 'WI',
// age: 100,
// alive: true,
// hobby: [ 'programming', 'music' ]
// }