- Object를 어떻게 serialize하여 JSON으로 변환할 수 있다.
- 직렬화된 JSON을 deserialize하여 Object화 할 수 있다.
- 데이터를 주고받는 가장 간단한 파일 format이다.
- 택스트를 기반으로 하여 가볍다.
- 가독성이 높다.
- key와 value로 데이터를 주고 받는다.
- 데이터를 주고 받을 때 직렬화하여 주고 받는다.
- 프로그래밍 언어와 플랫폼에 상관없이 사용이 가능하다.
Client 단에서 서버와 데이터를 주고 받을 때, key:value의 형태로 데이터를 주고 받는다.
// json.js side
let json = JSON.stringify(true);
console.log(json);
json = JSON.stringify(['apple','banana']);
console.log(json);
/*---------------------------------------------------------*/
//Object를 JSON으로 변환
const rabbit ={
name:'tori',
color:'white',
size:null,
birthDate:new Date(), //Date 결과가 String타입으로 변환되어 출력
jump: () =>{ //함수는 JSON으로 변환 불가능
console.log(`${name} can jump!`);
},
};
json = JSON.stringify(rabbit);
console.log(json);
/* 출력결과
{"name":"tori","color":"white","size":null
,"brithDate":"2022-05-15T15:17:05.149Z"}
*/
/*---------------------------------------------------------*/
//원하는 property만 JSON화하기
json = JSON.stringify(rabbit, ['name', 'color']);
console.log(json);
/* 출력결과
{"name":"tori","color":"white"}
*/
/*---------------------------------------------------------*/
//콜백함수를 사용하여 세밀하게 통제하기
json = JSON.stringify(rabbit, (key, value) => {
console.log(`key: ${key}, value: ${value}`);
return key === 'name' ? 'ellie' : value;
});
console.log(json);
/* 출력결과
key: , value: [object Object]
key: name, value: tori
key: color, value: white
key: size, value: null
key: brithDatw, value: new Date()값
key: jump, value: ())=> {
console.log(`${name} can jump!`);
}
{"name":"ellie","color":"white","size":null
,"brithDate":"2022-05-15T15:17:05.149Z"}
*/
json = JSON.stringify(rabbit);
const obj = JSON.parse(json);
console.log(obj);
/* 출력결과
{name:"tori", color:"white", size: null, brithDate:"2022-05-15T15:17:05.149Z"
*/
rabbit.jump(); //정상작동
obj.jump(); //에러발생, JSON으로 변환과정에서 누락
/*
JSON형태로 변환시 함수가 포함되지 않기 때문에 JSON에서 Obj타입으로 변환하여도
jump() 메서드는 사용할 수 없다.
*/
console.log(obj.birthDate.getDate()); //에러, String타입으로 JSON 변환이 되기 때문
console.log(obj.birthDate); //정상작동
/* 출력결과
2022-05-15T15:17:05.149Z
*/
/*---------------------------------------------------------*/
obj = JSON.parse(json, (key, value) =>{
//모든 키와 벨류 출력
console.log(`key: ${key}, value: ${value}`);
return value;
});
/* 출력결과
key: , value: [object Object]
key: name, value: tori
key: color, value: white
key: size, value: null
key: brithDatw, value: new Date()값
*/
/*---------------------------------------------------------*/
// obj에서 birthDate.getDate() 핸들링하기
obj = JSON.parse(json, (key, value) =>{
//모든 키와 벨류 출력
console.log(`key: ${key}, value: ${value}`);
return key === 'birthDate ? new Date(value) : value;
});
/* 출력결과
Date 값 출력
ex) 15 (작성날짜 15일 기준)
*/