본문 바로가기
Frontend/JavaScript

[JavaScript] JSON.parse() / JSON.stringify()

by 민두이 2023. 2. 8.
728x90
반응형

JSON 이란?

JavaScript Object Notation의 약자로 데이터를 문자열의 형태로 나타내기 위해 사용되는 데이터 포멧으로,

객체, 배열, 숫자, 문자열, 불리언, 널과 같은 다양한 데이터를 나타낼 수 있고 가독성이 좋음.

{
  "name": "멍멍",
  "birthYear": 2022,
  "age": 1,
  "isAnimal": true,
  "favoriteFood": ["껌", "사과"],
}

 

JSON.parse()

JSON 문자열 > JS(자바스크립트) 객체

parse() 메서드는 JSON 문자열을 인자로 받아 결과 값을 JS 객체로 반환해줌

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

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

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

JS 객체로 변환된 데이터는 . 혹은 [] 기호를 사용하여 각 속성에 접근할 수 있다.

 

JSON.stringify()

JS(자바스크립트) 객체 > JSON 문자열

stringify() 메서드는 JavaScript 객체를 인자로 받고 JSON 문자열을 반환

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""

 

 

728x90