본문 바로가기

JS

JS - JSON

 

JS 강의 필기 + 추가

JSON

javascript object notation


JSON.stringify

object to JSON

stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;

stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;

overloading: 함수의 이름은 같지만 전달하는 param에 따라서 각각 다른 방식으로 호출이 가능

let json= JSON.stringify(true);
console.log(json);  // true

json = JSON.stringify(['apple', 'banana']);
console.log(json);  // ["apple","banana"]

 

함수는 object에 있는 data가 아니기 때문에 json에 포함되지 않는다. JS에만 있는 symbol도 포함 안 됨.

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":"2020-12-17T02:19:17.083Z"}

 

replacer를 추가해 원하는 것만 골라서 json으로 변환할 수 있다. 콜백함수인 replacer에 array나 key-value를 줄 수 있다.

// array로 key를 줄 때
json = JSON.stringify(rabbit, ['name', 'color']);

console.log(json);  // {"name":"tori","color":"white"}

// key-value로 줄 때
json = JSON.stringify(rabbit, (key, value) => {
    return key === 'name' ? 'phin' : value;
    // key가 name일 때 phin로 넣고 name외에는 그대로 vlaue 사용
});

console.log(json);
// {"name":"ellie","color":"white","size":null,"birthDate":"2020-12-17T02:32:39.104Z"}

JSON.parse

JSON to object

parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;

json = JSON.stringify(rabbit);
console.log(json);
// json으로 변환했던 object를 다시 object로 변환
const obj = JSON.parse(json);
console.log(obj); // object 출력. toggle 클릭하면 key-value 정보를 볼 수 있음

json 변환과 parsing을 거치면서 변한 사항

rabbit - 최초 object

obj - json 변환과 parsing을 거쳐 다시 object가 된 것

1. method 손실

json 변환시 함수는 포함하지 않는다.

object rabbit에 있던 jump method를 rabbit.jump();로 호출하면 정상이지만,

obj.jump();로 호출하면 에러가 난다.

2. date object str화

rabbit에 있던 birthDate가 get Date()라는 object 자체였던 게 str으로 변환되었기 때문에 getDate()를 쓸 수 없다.

console.log(rabbit.birthDate.getDate()); // 17

console.log(obj.birthDate.getDate()); // 에러남

console.log(obj.birthDate); // str출력. 2020-12-17T02:44:25.342Z

 

reviver를 추가해 세밀하게 통제할 수 있다.

const obj2 = JSON.parse(json, (key, value) => {
    return key === 'birthDate' ? new Date(value) : value;
}); // key가 birthDate면 들어있는 value(str)를 Date object로 변환한다.

console.log(obj2.birthDate);    // Thu Dec 17 2020 11:53:45 GMT+0900 (대한민국 표준시)
console.log(obj2.birthDate.getDate());  // 17
// 이제 정상적으로 출력됨.

'JS' 카테고리의 다른 글

JS는 왜 이래요?  (0) 2021.03.13
JS - callback, promise  (0) 2020.12.26
JS - array  (0) 2020.12.24
JS - object  (0) 2020.12.23
JS - class  (0) 2020.12.22