2 분 소요

Object to JSON

stringify(obj)

배열을 json으로 변환

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

오브젝트를 json으로 변환

const rabbit = {
    name: 'tori',
    color: "white",
    size: null,
    birthDate: new Date(),
    jump: () => {
        console.log(`${name} can jump!`);
    },
};

let json = JSON.stringify(rabbit);
console.log(json); // {"name":"tori","color":"white","size":null,"birthDate":"2022-04-15T16:44:57.918Z"}

let json2 = JSON.stringify(rabbit, ['name']); // name만 json으로 변환
console.log(json2); // {"name":"tori"}

let json3 = JSON.stringify(rabbit, ['name', 'color']); // name과 color를 json으로 변환
console.log(json3); // {"name":"tori","color":"white"}

조금 더 세밀하게 통제하고 싶을 때, 콜백함수를 이용

const rabbit = {
    name: 'tori',
    color: "white",
    size: null,
    birthDate: new Date(),
    jump: () => {
        console.log(`${name} can jump!`);
    },
};

json = JSON.stringify(rabbit, (key, value) => {
    console.log(`key: ${key}, value: ${value}`);
    return value;
});

console.log(json);

출력 결과

key: , value: [object Object]
key: name, value: tori
key: color, value: white
key: size, value: null
key: birthDate, value: 2022-04-15T16:59:01.856Z
key: jump, value: () => {
        console.log(`${name} can jump!`);
    }
{"name":"tori","color":"white","size":null,"birthDate":"2022-04-15T16:59:01.856Z"}

출력 결과에서, 제일 처음으로 전달되는 것은 rabbit 오브젝트를 싸고 있는 제일 최상위 것이 전달됨
그 뒤부터 key와 value가 전달됨
🤔 만약 아래와 같이 리턴값을 바꾼다면?

json = JSON.stringify(rabbit, (key, value) => {
    console.log(`key: ${key}, value: ${value}`);
    // key가 name이면 ann으로 변경하고 key가 name이 아니면 오리지널 value 사용
    return key === 'name' ? 'ann' : value;
});

console.log(json);

출력 결과

key: , value: [object Object]
key: name, value: tori
key: color, value: white
key: size, value: null
key: birthDate, value: 2022-04-15T16:59:54.000Z
key: jump, value: () => {
        console.log(`${name} can jump!`);
    }
{"name":"ann","color":"white","size":null,"birthDate":"2022-04-15T16:59:54.000Z"}

name의 value가 ann으로 변경되었다.

JSON to Object

parse(json)

const rabbit = {
    name: 'tori',
    color: "white",
    size: null,
    birthDate: new Date(),
    jump: () => {
        console.log(`${name} can jump!`);
    },
};

let json = JSON.stringify(rabbit);

// json을 parse의 인자로 넣어주면 끝!
const obj = JSON.parse(json);
console.log(obj);

출력 결과

{
  name: 'tori',
  color: 'white',
  size: null,
  birthDate: '2022-04-15T17:02:41.317Z'
}

유의사항 1

기존의 rabbit이라는 오브젝트에는 jump라는 함수가 있었지만, obj에는 jump가 없다.
obj는 serialized 된 json으로부터 만든 오브젝트이기 때문이다.
(serialize 할 때, 데이터는 포함되지만 함수는 포함되지 않는다.)

rabbit.jump(); // 1
// obj.jump(); // 2

따라서 1번은 에러가 발생하지 않지만, 2번은 에러가 발생한다.

유의사항 2

기존의 rabbit이라는 오브젝트는 birthDate가 Date 타입이지만, obj의 birthDate는 String 타입이다.

console.log(rabbit.birthDate.getDate()); // 1
// console.log(obj.birthDate.getDate()); // 2

따라서 1번은 오늘의 날짜(일)를 반환하지만, 2번은 에러가 발생한다.

유의사항 2에 대해 세밀하게 통제하기 위해, 콜백함수를 이용

obj를 String 타입이 아닌 Date 타입으로 변활할 수 있도록!

const rabbit = {
    name: 'tori',
    color: "white",
    size: null,
    birthDate: new Date(),
    jump: () => {
        console.log(`${name} can jump!`);
    },
};

let json = JSON.stringify(rabbit);

const obj = JSON.parse(json, (key, value) => {
  // key가 birthDate이면 Date 타입으로 변환하고 key가 birthDate가 아니면 오리지널 value 사용
  return key === 'birthDate' ? new Date(value) : value;
});
console.log(obj);

이제 console.log(obj.birthDate.getDate());도 에러가 발생하지 않는다.

유용한 사이트 소개

JSON Diff 두 개의 json 파일의 다른 점을 찾아주는 사이트
JSON Beautifier json 포멧을 예쁘게 맞춰주는 사이트
JSON Parser json으로부터 object가 어떻게 표기되는지 확인할 수 있는 사이트
JSON Validator json 형식이 유효한지 확인할 수 있는 사이트

📁 참고

DreamCoding



💛 개인 공부 기록용 블로그입니다. 👻

맨 위로 이동하기