tech.junha.kr

노트/JavaScript

JSON

작성

1. JSON.stringify()

JSON.stringify(true);
 // 'true'

JSON.stringify(['apple', 'banana']);
// '["apple","banana"]'
const obj = {
    color: 'white',
    jump: () => {
        console.log('JUMP!');
    },
    birthDate: new Date(),
};
JSON.stringify(obj);
// {"color":"white","birthDate":"2023-04-27T09:23:34.929Z"}'
// 메서드는 serialize 되지 않음

JSON.stringify(obj, ['color']);
// '{"color":"white"}'
const replacer = function (key, value) {
    console.log(`key:${key} value: ${value}`)
    if (key === 'color'){
        return undefined;
    }
    return value;
}

JSON.stringify(obj, replacer);
// '{"birthDate":"2023-04-27T09:35:02.094Z"}'

2. JSON.parse()

string = JSON.stringify(obj);
const newObj = JSON.parse(string);
// {color: 'white', birthDate: '2023-04-27T09:35:02.094Z'}
// birthDate값은 date 객체에서 문자열로 변함
const newObj = JSON.parse(string, (key,value) => {
    console.log(`key:${key} value: ${value}`)
    return key === 'birthDate'? new Date(value) : value;
});
// {color: 'white', birthDate: Thu Apr 27 2023 18:35:02 GMT+0900 (동부 인도네시아 시간)}