HTTP
클라이언트와 서버가 어떻게 소통할지 정해놓은 규칙, 규약
XML
Markup 언어 중 하나
JSON
네트워크 통신에 사용하는 데이터는 string 타입
=> 객체(Object) 타입을 문자열 타입으로 변경해야함
=> 자바스크립트는 이 기능을 하는JSON.stringify
메서드를 제공.
JSON.stringify
: 인자로 전달된 객체를 JSON 데이터 포맷 규칙에 적합한 string 타입으로 변경함
JSON.parse
: JSON 데이터를 다시 객체타입으로 활용할 때 사용
Object를 어떻게 serialize 할 수 있는지
*Overloading : 함수 이름은 동일하지만 어떤, 몇 개의 parameter를 전달하냐에 따라 각각 다른 방식으로 호출이 가능한 함수
배열을 JSON으로 변환
let json = JSON.stringify(['apple', 'banana']); console.log(json); // ["apple","banana"]
double quote는 JSON의 규격 사항
객체를 JSON으로 변환
const rabbit = { name: "peter", color: "white", size: null, birthDate: new Date(), jump: () => { console.log(`${this.name} can jump!`); } }; const json = JSON.stringify(rabbit); console.log(json); // '{"name":"peter","color":"white","size":null,"birthDate":"2022-07-26T09:55:13.753Z"}'
Object가 stringify 되어서 출력됨
📌 이 때 함수는 Object에 있는 data가 아니기 때문에 제외되고Symbol
처럼 JS에만 있는 특별한 data도 json에 포함되지 않음
const json2 = JSON.stringify(rabbit, ['name', 'color']);
console.log(json);
// '{"name":"peter","color":"white"}'
내가 원하는 data만 출력하고 싶을 때 두 번째 인자에 속성의 key 값을 string 타입으로 배열로 전달하면 해당 property만 JSON으로 변환됨
const json3 = JSON.stringify(rabbit, (key, value) => { console.log(`key: ${key}, value: ${value}`); return value; }); console.log(json3); // key: , value: [object Object] // key: name, value: peter // key: color, value: white // key: size, value: null // key: birthDate, value: 2022-07-26T10:11:52.994Z // key: jump, value: function jump() { // console.log("".concat(_this.name, " can jump!"));} // {"name":"peter","color":"white","size":null,"birthDate":"2022-07-26T10:33:22.439Z"}
맨 처음 전달되는 data는 rabbit 객체를 싸고있는 제일 최상위 data
JSON to Object
const rabbit = { name: "peter", color: "white", size: null, birthDate: new Date(), jump: () => { console.log(`${this.name} can jump!`); } }; const json = JSON.stringify(rabbit); const obj = JSON.parse(json); // stringify된 object를 다시 object로 만들기 console.log(obj); // {name: 'peter', color: 'white', size: null, birthDate: '2022-07-26T10:37:34.825Z'} obj.jump(); // error
stringify(serialize) 할 때
jump()
method는 json에 포함되지 않기 때문에 다시 object로 만든obj
에서도jump()
는 실행될 수 없음console.log(rabbit.birthDate.getDate()); // 26 (현재 일자) console.log(obj.birthDate.getDate()); // error
stringify(serialize) 할 때
rabbit.birthDate
는birthDate: '2022-07-26T10:37:34.825Z'
라는 string으로 변환됨
이 string을 다시 object로 만들면birthDate
의 value가'2022-07-26T10:37:34.825Z'
가 되어서 Date object에서 사용할 수 있는getDate()
와 같은 method 사용 불가 (birthDate의 value는 그냥 단순 string이기 때문!)✍ reviver 함수를 써볼까요?
const obj = JSON.parse(json, (key, value) => { console.log(`key : ${key}, value : ${value}`); return key === "birthDate" ? new Date(value) : value; }); console.log(obj);
return key === "birthDate" ? new Date(value) : value;
는 birthDate라는 key를 만나면 해당 value를 new Date()에 전달한 값을 출력하고 아니면 그냥 value 그대로 return 해줌