2019/11/05 TIL

HANJIN·2019년 11월 4일
0

TIL

목록 보기
10/14

JSON.parse

syntax

JSON.parse(text[, reviver])

JSON 문자열의 구문을 분석하고, 그 결과에서 JavaScript 값이나 객체를 생성한다.
reviver 함수를 인수로 전달할 경우, 결과를 반환하기 전에 변형할 수 있다.

예제

var json = '{"result":true, "count":42}';
obj = JSON.parse(json);

console.log(obj.count);
// expected output: 42

console.log(obj.result);
// expected output: true

reviver 함수를 포함한 예제

JSON.parse('{"p": 5}', (key, value) =>
  typeof value === 'number'
    ? value * 2 // 숫자라면 2배
    : value     // 나머진 그대로
);

// { p: 10 }

JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => {
  console.log(key); // 현재 속성명 출력, 마지막은 빈 문자열("")
  return value;     // 변환하지 않고 그대로 반환
});

// 1
// 2
// 4
// 6
// 5
// 3 
// ""

iterator 객체 내의 후행 쉼표 사용불가

JSON.parse('[1, 2, 3, 4, ]'); // SyntaxError
JSON.parse('{"foo" : 1, }'); // SyntaxError

JSON.stringify

syntax

JSON.stringify(value[, replacer[, space]])

JavaScript 값이나 객체를 JSON 문자열로 변환한다. 선택적으로, replacer를 함수로 전달할 경우 변환 전 값을 변형할 수 있고, 배열로 전달할 경우 지정한 속성만 결과에 포함한다.

예제

console.log(JSON.stringify({ x: 5, y: 6 }));
// expected output: "{"x":5,"y":6}"

console.log(JSON.stringify([new Number(3), new String('false'), new Boolean(false)]));
// expected output: "[3,"false",false]"

console.log(JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] }));
// expected output: "{"x":[10,null,null,null]}"

console.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)));
// expected output: ""2006-01-02T15:04:05.000Z""

replacer 함수를 포함한 예제

function replacer(key, value) {
  if (typeof value === "string") {
    return undefined;
  }
  return value;
}

var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
var jsonString = JSON.stringify(foo, replacer); // {"week":45,"month":7}

replacer가 배열인 경우, 그 배열의 값은 JSON 문자열의 결과에 포함되는 속성의 이름을 나타낸다.

JSON.stringify(foo, ['week', 'month']);  
// '{"week":45,"month":7}', 단지 "week" 와 "month" 속성을 포함한다
profile
소프트웨어 엔지니어.

0개의 댓글