JS - JSON


JSON (JavaScript Object Notation) 은 값이나 객체를 나타내는 포맷으로, RFC 4627 에 정의되어 있다. 데이터 교환을 목적으로 많이 사용되고 있는 포맷이다.
예전에 생각없이 딥카피를 하려고 많이 썼었다.. ㅎㅎ; 알아두면 좋은 메서드들을 가지고 있다.

JSON 기본

  1. 주석을 쓸 수 없다.
  2. JSON 의 문자열은 로 감싸야한다.
  3. 프로퍼티 이름도 로 감싸야한다.
  4. 들어갈 수 있는 자료형은 아래와 같다.
    • 객체
    • 배열
    • 문자형
    • 숫자형
    • 불린형
    • null

JSON.stringify

객체를 JSON 으로 바꿔주는 메서드이다. 변환하는 객체 안의 메서드, 심볼형 프로퍼티, 값이 undefined 인 프로퍼티는 무시된다.
또한 순환 참조가 있을 경우 변환에 실패한다.

const json = JSON.stringify(valule [, replacer, space]);

  • value: 인코딩하려는 값
  • replacer: 인코딩하려는 프로퍼티의 배열, 매핑되는 함수
  • space: 서식에 추가되는 공백 문자 수
const me = {
  name: 'aredra',
  sayHi() {
    alert('Hi!');
  },
  [Symbol('id')]: 9999,
  age: undefined,
  job: 'developer',
  company: {
    name: 'haha',
    ceo: 'AZ',
  }
}

console.log(JSON.stringify(me));
console.log(JSON.stringify(me, ['name', 'job', 'company'], 2));

toJSON

인코딩 하려는 객체에 toJSON 메서드가 구현되어 있으면 JSON.stringify 는 이를 감지하고 해당 메소드를 호출한 결과를 반환해준다.

const me = {
  name: 'aredra',
  job: 'developer',
  company: {
    name: 'haha',
    ceo: 'AZ',
  },
  toJSON() {
    return this.name;
  }
}

console.log(me);

JSON.parse

JSON 포맷으로 인코딩된 객체를 다시 객체로 디코딩 해주는 메서드!

const obj = JSON.parse(str[, reviver]);

  • str: JSON 형태 문자열
  • reviver: (key, value) 쌍을 인자로 받는 함수로 값을 변경할 수 있다.
const testJson = `{
  "name": "aredra",
  "age": 9999,
  "birthDay": "1970-01-01T12:00:00.000Z"
}`

console.log(JSON.parse(testJson));
console.log(JSON.parse(testJson, (key, value) => {
  if (key === 'birthDay') {
    return new Date(value);
  }
  return value;
}));

출처: 모던 JavaScript 튜토리얼

Tags:

Categories:

Updated: