프론트엔드 개발

JSON 본문

Front-End/Javascript

JSON

태나미 2021. 3. 7. 17:42
JSON (JavaScript Object Notation)은 경량의 DATA-교환 형식이다. 이 형식은 사람이 읽고 쓰기에 용이하며, 기계가 분석하고 생성함에도 용이하다. 
JSON은 완벽하게 언어로부터 독립적이지만 C-family 언어 - C, C++, C#, Java, JavaScript, Perl, Python 그 외 다수 - 의 프로그래머들에게 친숙한 관습을 사용하는 텍스트 형식이다. 이러한 속성들이 JSON을 이상적인 DATA-교환 언어로 만들고 있다.

 

Json 특징

  • JSON stands for JavaScript Object Notation
  • JSON is a lightweight data-interchange format
  • JSON is "self-describing" and easy to understand
  • JSON is language independent *

JSON Example

Client 에서 server로 전송할 때 key와 value의 string type으로 변환해서 전송
server에서 client로 토끼라는 object로 변환해서 받아온다.

 

 

JSON 공부 포인트

1. object를 직렬화해서 데이터를 보여줄지
2. 직렬화된 데이터를 어떻게 object형식으로 보여줄지 

1. Object to JSON

const rabbit = {
  name: 'tokki',
  color: 'white',
  size: null,
  birthDate: new Date(),
  jump: () => {
    console.log(`${this.name} can jump`);
  }
};

let json = JSON.stringify(rabbit);
console.log(json);
// {"name":"tokki","color":"white","size":null,"birthDate":"2021-03-05T16:58:16.436Z"}

json = JSON.stringify(rabbit, ['name', 'color']);
console.log(json);
// {"name":"tokki","color":"white"}

json = JSON.stringify(rabbit, (key, value)=>{
  console.log(`key: ${key}, value: ${value}`);
  // key: , value: [object Object]
  // key: name, value: tokki
  // key: color, value: white
  // key: size, value: null
  // key: birthDate, value: 2021-03-07T08:04:19.114Z
  // key: jump, value: () => {
  //   console.log(`${this.name} can jump`);
  // }
  return key === 'name' ? 'taenam' : value; 
});

console.log(json);
// {"name":"taenam","color":"white","size":null,"birthDate":"2021-03-07T08:08:11.557Z"}

JSON.stringify된 rabbit을 jump함수가 console에서 찍히지 않은 것을 볼 수 있는데, 
함수는 object에 있는 data가 아니기 때문에 제외된다.

 

2. JSON to Object

// 위와 연결됨

const obj = JSON.parse(json);
console.log(obj);
// {name: "taenam", color: "white", size: null, birthDate: "2021-03-07T08:13:57.406Z"}

rabbit.jump();
// can jump

obj.jump();
// Uncaught TypeError: obj.jump is not a function

console.log(rabbit.birthDate.getDate());
// 7

console.log(obj.birthDate.getDate());
// Uncaught TypeError: obj.birthDate.getDate is not a function

// 다시 Date로 변환하고 싶을 때, callBack 함수를 이용할 수 있다.
obj = JSON.parse(json, (key, value) => {
    return key==="birthDate" ? new Date() : value;
});

console.log(obj.birthDate.getDate());
// 7

 

- obj.jump()의 TypeError

변환한 오브젝트는 serialize가 된(스트링으로 만들어진 JSON)으로 부터

다시 Object를 만들었기 때문에, 함수는 serialize될 때, 포함이 되어있지 않았다.

 

- obj.birthDate.getDate()의 TypeError

obj의 birthDate는 serialize되어서 string 형태로 되어있는데, 
이것을 다시 object화 시킬때도 string으로 할당이 되어, error가 났다

 

 

출처: www.youtube.com/watch?v=FN_D4Ihs3LE&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=10

JSON 관련 유용한 사이트: jsondiff.com/

 

'Front-End > Javascript' 카테고리의 다른 글

null 과 undefined 차이점  (0) 2021.03.14
Regular Expression  (0) 2021.03.09
javascript - object  (0) 2021.02.07
javascript - 객체지향언어, class  (0) 2021.02.03
javascript - function  (0) 2021.01.31
Comments