JSON: JavaScript Object Notation
- 속성-값 쌍(attribute–value pairs), 배열 자료형(array data types) 또는 기타 모든 시리얼화 가능한 값(serializable value) 또는 키-값 쌍으로 이루어진 데이터 오브젝트를 전달하기 위해 인간이 읽을 수 있는 텍스트를 사용하는 개방형 표준 포맷
- 비동기 브라우저/서버 통신(AJAX)을 위해, 넓게는 XML(AJAX가 사용)을 대체하는 주요 데이터 포맷
- 본래는 자바스크립트 언어로부터 파생되어 자바스크립트의 구문 형식을 따르지만 언어 독립형 데이터 포맷
- 프로그래밍 언어나 플랫폼에 독립적이므로, 구문 분석 및 JSON 데이터 생성을 위한 코드는 C, C++, C#, 자바, 자바스크립트, 펄, 파이썬 등 수많은 프로그래밍 언어에서 쉽게 이용할 수 있음
특징
- simplest data interchange format
- lightweight text-based structure
- easy to read
- key-value pairs
- used for serialization and transmission of data between the network the network connection
- independent programming language and platform
1. Object to JSON
- stringify(obj)
let json = JSON.stringify(true);
console.log(json); // true
json = JSON.stringify(['apple', 'banana']);
console.log(json); // ["apple", "banana"]
const rabbit = {
name: 'tori',
color: 'white',
size: null,
birthDate: new Date(),
jump: () => { // 함수는 오브젝트에 있는 데이터가 아니기 때문에 JSON으로 출력되지 않음
console.log(`${this.name} can jump!`);
},
};
json = JSON.stringify(rabbit);
console.log(json); // {"name":"tori","color":"white","size":"null","birthDate":"2020-05-29"}
// JSON을 세밀하게 통제하고 싶을 때
json = JSON.stringify(rabbit, ['name', 'color', 'size']);
console.log(json); // {"name":"tori","color":"white","size":"null"}
json = JSON.stringify(rabbit, (key, value) => {
console.log(`key: ${key}, value: ${value}`);
return key === 'name' ? 'ellie' : value;
});
console.log(json); // {"name":"ellie","color":"white","size":"null","birthDate":"2020-05-29"}
2. JSON to Object
- parse(json)
json = JSON.stringify(rabbit);
const obj = JSON.parse(json);
console.log(obj); // {name:"tori", color:"white", size:null, birthDate:"2020-05-29"}
const obj = JSON.parse(json, (key, value) => {
console.log(`key: ${key}, value: ${value}`);
return key === 'birthDate' ? new Date(value) : value;
});
console.log(obj); // {name:"tori", color:"white", size:null, birthDate:2020-05-29}
rabbit.jump(); // can jump!
// obj.jump(); // jump는 오브젝트에 포함되지 않았으므로 error!
console.log(rabbit.bitrhDate.getDate()); // 29
console.log(obj.bitrhDate.getDate()); // 29
유용한 사이트
- JSON Diff checker: 코드를 비교할 수 있어 문제를 디버깅할 때 유용함
- JSON Beautifier/editor: 서버에서 받아온 포맷이 깨졌을 때 포맷을 복구할 수 있음
- JSON Parser: JSON을 object 형태로 확인할 수 있음
- JSON Validator: JSON 데이터가 유효한지 확인할 수 있음
'JavaScript' 카테고리의 다른 글
callback (0) | 2023.06.22 |
---|---|
function (0) | 2023.06.13 |
Array APIs (0) | 2023.06.12 |
Array (0) | 2023.06.12 |
Object (1) | 2023.06.09 |