Stack/JavaScript
[JS/JSON] JSON(; JavaScript Object Notaion)
7ingout
2022. 6. 14. 12:29
JSON(JavaScript Object Notaion)
서버와 데이터를 전송할 때 사용되는 데이터포맷
자바스크립트의 객체를 보고 만든 데이터 포맷
텍스트를 기반으로 하여 가벼움
데이터를 직렬화하여 전송할 때 쓰임
프로그램 언어나 플랫폼에 상관없이 쓸 수 있음
XML -> JSON
자바스크립트 객체 -> 직렬화-> JSON
JSON -> 자바스크립트 객체
1. object to JSON
JSON.stringify(obj)
2. JSON to object
JSON.parse(json)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const rabbit = {
name: 'tory',
color: 'white',
size: 'small',
birthDay: new Date(),
jump: () => {
console.log("점프할 수 있음");
}
}
// JSON.stringify(obj)
let json = JSON.stringify(rabbit);
console.log(rabbit);
console.log(json);
// JSON.parse(json)
let obj = JSON.parse(json);
console.log(obj);
let obj2 = JSON.parse(json, (key, value)=> {
return key === 'birthDay' ? new Date(value) : value;
})
console.log(obj2);
</script>
</body>
</html>