📚강의록📚/스파르타)React
React숙련주차18(JSON)
과부하가즈아
2023. 7. 1. 18:05
JSON(JavaScript Object Notation)
자바스크립트 객체 문법에 토대를 둔, 문자 기반의 데이터 교환 형식
일반적인 JSON 구조는 자바스크립트 객체 리터럴 작성법을 따른다. 자바스크립트의 원시 자료형인 문자열, 숫자, 불리언을 가질 수 있고 중첩된 계층 구조 또한 가질 수 있다.
📌비슷한 것 뿐, 작은 따옴포(’’)가 아닌 끝 따옴표(””)만이 허용된다
{
"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에서는 사용하는 메서드 두 가지를 기억하면 된다.
1. JS Object -> JSON으로 바꾸는 stringify()
2. JSON -> JS Object으로 바꾸는 parse()
stringify()_string화 시킨다, 문자열화 시킨다
JSON.stringify(JS Object)를 통해서 자바스크립트 객체 → JSON 문자열 변환, 네트워크를 통해 객체를 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""
console.log(JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] }));
// Expected output: "{"x":[10,null,null,null]}"
>> 지원이 안되는 구조도 있다.
parse()
JSON.parse(json)를 통해 JSON 문자열 → 자바스크립트 객체 변환, 네트워크 통신의 결과를 통해 받아온 JSON 문자열을 프로그램 내부에서 사용하기 위해 JS 객체로 변환할 때 사용.
네트워크 통신의 결과 즉, 서버에서 클라이언트로 데이터를 보내줄 때 JSON형태로 보내주기 때문에 이게 필요한 것이다.
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
가짜 서버(= fake server, mock API server)