TIL JavaScript from Dream Coding(7)

doradora523·2022년 5월 30일
0

DreamCoding

목록 보기
7/9
post-thumbnail

JSON

JavaScript Object Notation

1. Object to JSON (stringify)

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(),
  symbol: Symbol('id'), // json(X) 
  jump: () => { // json(X) 
    console.log(`${name} can jump!`);
  },
};

json = JSON.stringify(rabbit);
console.log(json); 
// {"name":"tori","color":"white","size":null,"birthDate":"2022-05-29T15:40:22.670Z"}

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}`);
  // key: , value: [object Object]
  // key: name, value: tori
  // key: color, value: white
  // key: size, value: null
  // key: birthDate, value: 2022-05-29T15:40:22.670Z
  // key: jump, value: () => {
  //  console.log(`${name} can jump!`);
  //}
  return key === 'name' ? 'amanda' : value;
});
console.log(json);
{"name":"amanda", "color":"white", "size":null, "birthDate":"2022-05-29T15:40:22.670Z"}

2. JSON to Object (parse(json))

json = JSON.stringify(rabbit);

// 1
const obj = JSON.parse(json);
console.log(obj);
// {name:"amanda", color:"white", size:null, birthDate:"2022-05-29T15:40:22.670Z"}
rabbit.jump();
// can jump!
obj.jump();
// Uncaught TypeError: obj.jump is not a function

console.log(rabbit.birthDate.getDate()); // 29 // object자체
console.log(obj.birthDate); // 2022-05-29T15:40:22.670Z // string으로 변환 됨

// 2
const obj = JSON.parse(json, (key, value) => {
  console.log(`key: ${key}, value: ${value}`);
  // key: name, value: tori
  // key: color, value: white
  // key: size, value: null
  // key: birthDate, value: 2022-05-29T15:40:22.670Z
  // key: , value: [object Object]
  return key === 'birthDate' ? new Date(value) : value;
});
console.log(obj.birthDate.getDate()); // 29

0개의 댓글