JS2_08_JSON

charl hi·2021년 11월 29일

JS2

목록 보기
6/6

JSON

  • JavaScript Object Notation
  • simplest data interchange format
  • lightweight text-based structure
  • easy to read
  • key-value pairs({key:value})
  • used for serialization(직렬화) and transmission of data between the network the network connection
  • independent programming language and platform



Object to JSON

JSON.stringify(obj)

  • 받은 객체를 그대로 문자열로
let json = JSON.stringify(true);
console.log(json, typeof json);

json = JSON.stringify(["apple", "banana"]);
console.log(json, typeof json);

const rabbit = {
  name: "tori",
  color: "white",
  size: null,
  birthDate: new Date(),
  // symbol: Symbol("id"),
  jump: () => {
    console.log(`${this.name} can jump!`);
  },
};

json = JSON.stringify(rabbit);
console.log(json);
//함수는 객체의 정보가 아니기 때문에 없음
//symbol은 자바스크립트에만 있는 타입이므로 안됨



JSON.stringify(obj, replacer배열|함수)

  • 내가 원하는 정보만
  • 처음엔 최상위 객체가 전달된다.
json = JSON.stringify(rabbit, ["name", "color", "size"]);
console.log(json);
console.log("------------------------------------------------");

json = JSON.stringify(rabbit, (key, value) => {
  console.log(`key: ${key}, value: ${value}`);
  // return value;
  return key === "name" ? "ellie" : value;
});
//처음엔 **최상위 객체**가 전달된다.
console.log(json);




JSON to Object

JSON.parse(json문자열, reviver배열|함수))

json = JSON.stringify(rabbit);
console.log(json);
console.log("-------------------------------------------------");


  • 마지막에 최상위 객체가 전달된다.
const obj = JSON.parse(json, (key, value) => {
  console.log(`key: ${key}, value: ${value}`);
  // return value;
  return key === "birthDate" ? new Date() : value;
});
//마지막에 **최상위 객체**가 전달된다.
console.log(obj);	//객체!!!



📢📢주의!!!

rabbit.jump();
obj.jump(); //오류 : jump()함수가 없다.
console.log("------------------------------------------------");


console.log(rabbit.birthDate.getDate());
// console.log(obj.birthDate.getDate()); //오류 : 그냥 parse()로 하면, JSON으로 변환될 때 이미 string으로 저장됨
console.log(obj.birthDate);
console.log(obj.birthDate.getDate());

0개의 댓글