parse
→ parse(json)
parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;
(개념설명)
JSON의 string 데이터를 any 의 어떤 타입의 object 로 변환이 되고,
reviver? 을 전달해도 되고 안 해도 되는 callback 함수가 있다.
즉, string을 object 로 변환할 떄, object가 만들어지는 과정을 조금더 세밀하게 조정하고 싶다면
reviver 함수를 이용하면 된다.
Converts a JavaScript Object Notation (JSON) string into an object.
(JSON (JavaScript Object Notation) 문자열을 객체로 변환합니다.)
@param text A valid JSON string.
(@param text 유효한 JSON 문자열입니다.)
@param reviver A function that transforms the results. This function is called for each member of the object.
(@param reviver 결과를 변환하는 함수. 이 함수는 개체의 각 구성원에 대해 호출됩니다.)
If a member contains nested objects, the nested objects are transformed before the parent object is
(멤버에 중첩 된 개체가 포함 된 경우 중첩 된 개체는 상위 개체보다 먼저 변형됩니다.)
@param text(string)
const rabbit = {
name: 'tori',
color: 'white',
size: null,
birthDate: new Date(),
jump: () => {
console.log(`${name} can Jump!`);
return 1;
}
//symbol: Symbol("id")
};
json = JSON.stringify(rabbit);
// string 을 obj object로 변환
let obj = JSON.parse(json);
console.log(obj); // {name: "tori", color: "white", size: null, birthDate: "2021-03-18T08:46:50.343Z"}
// ※ 주의할 점
rabbit.jump(); // rabbit 객체 안에는 jump() 라는 함수가 존재하지만
//obj.jump(); // ※ JSON에서 Object로 변환된 obj에서는 jump() 라는 함수가 존재하지 않는다.
// rabbit object 를 JSON 으로 변환하는 과정에서 jump 함수는 string 변환에 포함되지 않았기 때문이다.
//※ jump와 같은 함수는 JSON 의 string의 변환에 포함되지 않았기 때문에
@param text(string), @param reviver
// string 조정하여 변환하기
obj = JSON.parse(json, (key, value) => {
console.log(`key: ${key}, value: ${value}`);
return key === 'birthDate' ? new Date(value) : value;
//return value;
});
console.log(obj);
// {name: "tori", color: "white", size: null, birthDate: Thu Mar 18 2021 18:13:48 GMT+0900 (대한민국 표준시)}
console.log(rabbit.birthDate.getDate()); // 18
console.log(obj.birthDate.getDate()); // 18