[Javascript] JSON 다루기 (Javascript 제대로 알고 쓰자) - 7

강준혁·2020년 12월 4일
0

이번에는 개발을 하면서 자주 접하게 되는 JSON을 JS 에서 다루는 방식에 대해 얘기해보고자 한다.

JSON 객체

JSON 객체는 JS의 기본 내장객체로, 다음과 같이 두가지의 메서드를 제공한다.

  • JSON.stringify : 객체를 JSON으로 변환
  • JSON.parse : JSON을 객체로 변환

JSON.stringify

JSON.stringify 의 전체 문법은 다음과 같다.

let json = JSON.stringify(value[, replacer, space])
  • value: 인코딩 하려는 값
  • replacer: JSON으로 인코딩 하길 원하는 프로퍼티가 담긴 배열 또는 매핑 함수 function(key, value)
  • space: 서식 변경 목적으로 사용할 공백 수

호출 시 무시되는 프로퍼티

JSON.stringify 는 함수 프로퍼티, 심볼형 프로퍼티, 값이 undefined인 프로퍼티는 무시하고 동작한다.

let user = {
  sayHi() {
    console.log('Hello'); 
  }
  [Symbol("id")]: 1,
  something: undefined
}
console.log(JSON.stringify(user)); // {} 

원하는 프로퍼티만 직렬화 하기

replacer 에 배열을 사용하는 경우

let order = {
  order_id: 1,
  order_status: '배송중',
  order_item: {
    product_name: '원피스',
    product_cnt: 2
  }
}

console.log(
  JSON.stringify(order, ['order_id', 'order_item', 'product_name'])
);
/*
{"order_id":1,"order_item":{"product_name":"원피스"}}
*/

replacer 에 함수를 사용하는 경우

...
console.log(
  JSON.stringify(order, (key, value) => {
    return key == 'order_status' || key == 'product_cnt' ? undefined : value;
  })
);
/*
{"order_id":1,"order_item":{"product_name":"원피스"}}
*/

커스텀 'toJSON'

객체에 toJSON 이라는 메서드가 구현되어있으면 해당 메서드가 우선적으로 호출되어 직렬화가 진행된다.

let order = {
  order_id: 1,
  order_status: '배송중',
  order_item: {
    product_name: '원피스',
    product_cnt: 2
  },
  toJSON() {
    return 1;
  }
}

console.log(JSON.stringify(order)); // 1

JSON.parse

JSON.parse 의 전체 문법은 다음과 같다.

let value = JSON.parse(str, [reviver]);
  • str: JSON 형식의 문자열
  • reviver: function(key, value) 형태의 함수로 값 변경 가능.

reviver 사용하기

const order_json = `
{
    "order": {
        "order_id": "1234",
        "order_status": "배송중",
        "order_item": {
          "product_name": "상품1",
          "product_cnt": 2
        }
    }
}
`
function reviver(root, cls) {
    return (key, value) => {
        if (key == root) return new cls(value);
        else return value;
    }
}

class Order {
    order_id;
    order_status;
    order_item;

    constructor({order_id, order_status, order_item}) {
        this.order_id = order_id;
        this.order_status = order_status;
        this.order_item = new OrderItem(order_item);
    }
}
class OrderItem {
    product_name;
    product_cnt;
    constructor({product_name, product_cnt}) {
        this.product_name = product_name;
        this.product_cnt = product_cnt;
    }
}

console.log(JSON.parse(order_json, reviver('order', Order)));
/*
{
  order: Order {
    order_id: '1234',
    order_status: '배송중',
    order_item: OrderItem { product_name: '상품1', product_cnt: 2 }
  }
}
*/
profile
백엔드 개발자

0개의 댓글