1. JSON
// JSON 데이터를 문자열로 변환하여 변수에 할당 하였다 가정
const jsonString = `
{
"name": "Kim min tae",
"age": 30,
"bloodType": "B"
}
`;
- json은 key에 더블쿼터("")를 씌워주어야 한다.
- json은 싱글쿼터('')는 지원하지 않는다. 더블쿼터("")만 지원한다.
- json은 property 마지막에 콤마(,)를 찍으면 오류가 발생하므로 주의
// (1) json 데이터를 객체로 변환
const myJson = JSON.parse(jsonString);
console.log(myJson); // { name: 'Kim min tae', age: 30, bloodType: 'B' }
console.log(myJson.name); // Kim min tae
// (2) json객체를 문자열로 변환
console.log(JSON.stringify(myJson));
// "{"name":"Kim min tae","age":30,"bloodType":"B"}"
// (3) json데이터를 객체로 변환 시 혹시 모를 error 처리를 위해 try catch 문과 함께 사용한다.
try {
const parseJson = JSON.parse(jsonString);
console.log(parseJson);
} catch (e) {
console.log('다시한번 시도해 주세요.');
}