-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.js
More file actions
52 lines (42 loc) · 1.35 KB
/
json.js
File metadata and controls
52 lines (42 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// JSON
// JavaScript Object Notation
// 1. Object to JSON
// stringify(obj)
let json = JSON.stringify(true)
console.log(json) // true
json = JSON.stringify(['apple','banana'])
console.log(json) // ["apple","banana"]
const rabbit = {
name : 'tori',
color : 'white',
size : null,
birthDate : new Date(),
jump: function(){
console.log(`${this.name} can jump!`)
}
}
json = JSON.stringify(rabbit)
console.log(json) // {"name":"tori","color":"white","size":null,"birthDate":"2021-06-02T14:52:27.482Z"}
json = JSON.stringify(rabbit,['name','color','size'])
console.log(json) // {"name":"tori","color":"white","size":null}
json = JSON.stringify(rabbit,(key,value)=>{
console.log(`key : ${key}, value : ${value}`);
return key==='name'? 'ellie' : value
})
console.log(json) // {"name":"ellie","color":"white","size":null,"birthDate":"2021-06-02T14:52:27.482Z"}
// 2. JSON to Object
// parse(json)
console.clear()
json = JSON.stringify(rabbit)
let obj = JSON.parse(json)
console.log(obj)
rabbit.jump()
// obj.jump() // 오류 발생
console.log(rabbit.birthDate.getDate())
// console.log(obj.birthDate.getDate()) // 오류 발생
obj = JSON.parse(json,(key,value)=>{
console.log(`key : ${key}, value : ${value}`);
return key ==='birthDate' ? new Date(value): value
})
console.log(obj)
console.log(obj.birthDate.getDate())