ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • JSON과 JSON.stringify, JSON.parse
    JavaScript 2023. 1. 16. 08:50

    JSON(JavaScript Object Notation)은 데이터 교환을 위해 만들어진 객체 형태의 포맷이다.

    오늘날에는 자바나 파이썬과 같은 언어에서도 많이 사용된다.

    // JSON 예시
    {
      "text": "Hi, I am human",
      "readonly": true,
      "creadtedYear": 2019
    }
    • JSON은 자바스크립트의 객체와 유사한 형태를 띄고 있지만, JSON에는 또 다른 규칙들이 있다.
      🥙 자바스크립트 객체에서 는 따옴표 없이 쓸 수 있지만,
      JSON에서는 반드시 큰 따옴표를 붙여야 한다.
      🥨 자바스크립트 객체에서는 문자열의 값에 '나 "나 `와 같이 어떠한 형태의 따옴표도 사용할 수 있지만,
      JSON에서는 반드시 큰따옴표로 감싸야 한다.

    🍝 깊은 복사를 할 때에도 사용될 수 있다. parse후 다시 stringify하여 다른 변수에 할당하면, 깊은 복사가 된다.

    객체와 JSON 사이의 변환

    JSON.stringify JSON.parse을 이용하면 객체와 JSON을 서로 쉽게 변환할 수 있다.

    배열이나 객체를 비교할 때, 둘은 참조형 타입이므로 단순 비교가 어려운데, JSON의 형태로 변경하여 비교하면 쉽게 둘을 비교할 수 있다.

    + 참조형 데이터를 비교하는데 사용할 수 있다.

    const message = {
      "text": "Hi, I am human",
      "readonly": true,
      "creadtedYear": 2019,
    }
    
    const jsonMessage = JSON.stringify(message);
    console.log(jsonMessage);
    // '{"text":"Hi, I am human","readonly":true,"creadtedYear":2019}'
    
    const objectMessage = JSON.parse(jsonMessage);
    console.log(objectMessage);
    // {text: 'Hi, I am human', readonly: true, creadtedYear: 2019}
    • 배열의 비교
    let arrays1 = [1, 2, [3, 4, 5], 4, 5];
    let arrays2 = [1, 2, [3, 4, 5], 4, 5];
    
    console.log(arrays1 === arrays2); // false
    
    let arrays1Json = JSON.stringify(arrays1);
    let arrays2Json = JSON.stringify(arrays2);
    
    console.log(arrays1Json === arrays2Json); // true
    
    • 객체의 비교
    const message1 = {
      "text": "Hi, I am human",
      "readonly": true,
      "creadtedYear": 2019,
      "receiver": ["Lee", "park", "ki"],
    }
    
    const message2 = {
      "text": "Hi, I am human",
      "readonly": true,
      "creadtedYear": 2019,
      "receiver": ["Lee", "park", "ki"],
    }
    
    console.log(message1 === message2); // false;
    
    let message1Json = JSON.stringify(message1);
    let message2Json = JSON.stringify(message2);
    
    console.log(message1Json === message2Json); // true

     

    참조형 변수를 JSON.stringify 후 JSON.parse를 하여 복사할 수 있지만, 내부에 Date 객체나 함수 등은 제대로 복사할 수 없다.

Designed by Tistory.