JSON
(Javascript Object Notation)
: 데이터를 구조화하여 저장하거나 전송할 때 사용하는 경량 데이터 교환 형식
- 사람과 기계 모두 읽기 쉽고 작성하기 쉬운 텍스트 형식
- 웹에서 서버와 클라이언트 간에 데이터를 주고받을 때 사용❗
JSON.stringify()
: 서버에 보낼 때, 자바스크립트 객체를 JSON 문자열로 변환
- 코드 내용 👉 문자 형태로 바꿔줌
- 객체, 배열 등 가능
const user = {
nickname: 'tiger',
age: 44
}
JSON.stringfy(user);
// '{"nikname":"tiger","age":44}'
JSON.parse();
: 서버에서 받을 때, JSON 문자열을 자바스크립트 객체로 변환
- 서버로부터 받은 데이터(문자 형태) 👉 코드로 바꿔줌
- 문자 해석
try {
const data = JSON.stringify({
"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"
}
})
const user = JSON.parse(data);
console.log(user.name); // Leanne Graham
console.log(user.value);
if (!user.value) {
throw new ReferenceError('해당 키 값은 존재하지 않습니다.')
}
} catch (error) {
console.log('JSON Error : ' + error.message);
}