JSON과 parse(), stringify()

JSON Ajax JavaScript

문제점 😅

이전글 jQuery를 통한 Ajax 사용에서 Ajax 파라미터 중 data를 JSON으로 변환하여 작성했다. JSON에 대해서 짚고 넘어가보자.

해결책 😏

JSON이란 ?

JSON (JavaScript Object Notation)은 경량 데이터 교환 형식으로, JavaScript 객체 리터럴 문법을 따른다. 객체, 배열, 숫자, 문자열, 불리언(Boolean), 널(Null) 등 다양한 데이터를 "Key": "Value" 형식으로 나타낼 수 있다.

{
  "squadName": "Super hero squad",
  "homeTown": "Metro City",
  "formed": 2016,
  "secretBase": "Super tower",
  "active": true,
  "members": [
    {
      "name": "Molecule Man",
      "age": 29,
      "secretIdentity": "Dan Jukes",
      "powers": ["Radiation resistance", "Turning tiny", "Radiation blast"]
    },
    {
      "name": "Madame Uppercut",
      "age": 39,
      "secretIdentity": "Jane Wilson",
      "powers": [
        "Million tonne punch",
        "Damage resistance",
        "Superhuman reflexes"
      ]
    },
    {
      "name": "Eternal Flame",
      "age": 1000000,
      "secretIdentity": "Unknown",
      "powers": [
        "Immortality",
        "Heat Immunity",
        "Inferno",
        "Teleportation",
        "Interdimensional travel"
      ]
    }
  ]
}

JSON.parse()

JSON.parse() 함수는 JSON 문자열의 구문을 분석하고, 그 결과에서 JavaScript 값이나 객체를 생성한다.

 JSON.parse(text[, reviver])
console.log( JSON.parse("{}") ); // {}
console.log( JSON.parse("true") ); // true
console.log( JSON.parse('"foo"') ); // "foo"
console.log( JSON.parse('[1, 5, "false"]') ); // [1, 5, "false"]
console.log( JSON.parse("null") ); // null

// reviver 함수 파라미터 추가.
const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
const obj = JSON.parse(text, (key, value) => {
                  if (key == "name") {
                        return `Say My Name ${value}`;
                  } else if (key == "birth") {
                        return `My Birth is ${value}`;
                  } else {
                        return value;
                  }
});

console.log(obj);
// {name: 'Say My Name John', birth: 'My Birth is 1986-12-14', city: 'New York'}

JSON.stringify()

JSON.stringify() 함수는 JavaScript 값이나 객체를 JSON 문자열로 변환한다.

JSON.stringify(value[, replacer[, space]])
let myJsonData = {
                  foundation: "Mozilla",
                  model: "box",
                  week: 45,
                  transport: "car",
                  month: 7
                  };

console.log( JSON.stringify(myJsonData) );
// {"foundation":"Mozilla","model":"box","week":45,"transport":"car","month":7}

console.log( JSON.stringify(myJsonData, ["foundation", "month"]) ); 
// {"foundation":"Mozilla","month":7}

console.log( JSON.stringify(myJsonData, ["week", "transport"], 3) );
/*
{
   "week": 45,
   "transport": "car"
}
*/

마무리 😎

매개변수에 대해서 상세한 내용은 반드시 아래 mozilla 도큐먼트를 읽어보자.

참고문헌 📝

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/JSON
https://developer.mozilla.org/ko/docs/Learn/JavaScript/Objects/JSON
https://www.daleseo.com/js-json/
https://www.w3schools.com/js/js_json_parse.asp