-
자바스크립트 객체 표기법 vs JSON(JavaScript Object Notation)JavaScript/Webdevelopment 2022. 12. 26. 19:13
JSON
[ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } }, ... ]
JA
Json 타입을 JavaScript타입으로 바꿔주기
JSON.parse()
fetch('https://jsonplaceholder.typicode.com/users') // JSON 객체 출력 .then((response) => response.text()) .then((result) => {console.log( typeof result);}); // JSON의 타입은 String 이다
fetch('https://jsonplaceholder.typicode.com/users') // JSON 객체 출력 .then((response) => response.text()) .then((result) => {const users = JSON.parse(result)}); // JSON 객체로 바꿔주기
자바스크립트 객체를 리퀘스트에 JSON 데이터로 담아 보낼 때는, (A) 자바스크립트 객체를 string 타입의 JSON 데이터로 변환해줘야 합니다.(Serialization)
JSON.stringtify
// JS객체를 json의 string 타입으로 변환 ( Serilazation) const obj = { x:1, y:2 }; const jsonString = JSON.stringify(obj); console.log(obj); // {x: 1, y: 2} console.log(jsonString); // {"x":1,"y":2}
서버로부터 받은 리스폰스의 내용이 JSON 데이터일 때는, (B) string 타입의 JSON 데이터를 자바스크립트 객체로 변환해줘야 합니다.(Deserialization)
JSON.parse
// Deserilazation, json의 string 타입을 JS 객체로 변환한다 const jsonString = '{"x": 1, "y": 2}'; const obj = JSON.parse(jsonString); console.log(jsonString); // {"x": 1, "y": 2} console.log(obj); // {x: 1, y: 2}
fetch('https://jsonplaceholder.typicode.com/users') // response의 내용을 추출하기 위해서 response.text()를 호출 .then((response) => response.text()) // return값인, promise객체(json 데이터를 품고있는)를 리턴 (result) // json의 string타입 데이터를 deserialzation 한다 .then((result) => { const users = JSON.parse(result); }); // text말고 json()사용하기 fetch('https://jsonplaceholder.typicode.com/users') .then((response) => response.json()) .then((result) => { const users = result; });
'JavaScript > Webdevelopment' 카테고리의 다른 글
상태코드(Status_Code) (0) 2023.01.01 Fetch함수 (0) 2022.12.18 웹 개발 시작하기 (0) 2022.12.07 Request (0) 2022.09.07