9. JS Basic (json - stringify(obj), perse(json))

Changmok LEE·2023년 2월 10일

json

JavaScript Object Notation

1. Object to JSON

stringify(obj)

interface JSON {
    /**
     * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
     * @param value A JavaScript value, usually an object or array, to be converted.
     * @param replacer A function that transforms the results.
     * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
     */
    stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
    /**
     * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
     * @param value A JavaScript value, usually an object or array, to be converted.
     * @param replacer An array of strings and numbers that acts as an approved list for selecting the object properties that will be stringified.
     * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
     */
    stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;
  // overhead == 같은 이름으로 있는 것들(전달 인자에 따라 다르게 호출 된다)
}
let json = JSON.stringify(true);
console.log(json); // true

json = JSON.stringify(['apple', 'banana']);
console.log(json); // ["apple", "banana"] (쌍따옴표가 json의 규격사항)

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

json = JSON.stringify(rabbit);
console.log(json); // { "name":"tori",  ~ etc ~ , "birthDAte":"2023~~~~" }
/* 함수는 object에 있는 데이터가 아니기 때문에 포함 X,
symbol 같은 js에만 있는 특별한 데이터도 json에 포함되지 않는다 */

// replacer 사용 (property 이름 지정해줌)
json = JSON.stringify(rabbit, ["name"]);
console.log(json); // { "name":"tori" }

// replacer 사용 (callback 함수 사용)
// replacer?: ((this: any, key: string, value: any) => any)
json = JSON.stringify(rabbit, (key, value) => {
    console.log(`key: ${key}, value: ${value}`);
    return value;
});
console.log(json); 
// key: , value: [Object object](첫 값은 rabbit(object)감싸고 있는 최상의 값이 출력)  
// key: name, value : tori ...

json = JSON.stringify(rabbit, (key, value) => {
    console.log(`key: ${key}, value: ${value}`);
    return key === 'name' ? 'eelkom' : value;
});
console.log(json); 
// key: , value: [Object object]  
// key: name, value :eelkom ...

2. JSON to object

perse(json)

interface JSON {
    /**
     * Converts a JavaScript Object Notation (JSON) string into an object.
     * @param text A valid JSON string.
     * @param reviver A function that transforms the results. This function is called for each member of the object.
     * If a member contains nested objects, the nested objects are transformed before the parent object is.
     */
    parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;
}
json = JSON.stringify(rabbit); // object to json
const obj = JSON.parse(json);  // json to object
console.log(obj); // { "name":"tori",  ~ etc ~ , "birthDAte":"2023~~~~" }

rabbit.jump(); // o
obj.jump(); // X (json으로 변환 할 때 포함 안됨)

console.log(rabbit.birthDAte.getDate()); // o
console.log(obj.birthDAte.getDate()); // X(string 값으로 변환 되었기 때문에)


// reviver 사용
// reviver?: ((this: any, key: string, value: any) => any)
json = JSON.stringify(rabbit); // object to json
const obj = JSON.parse(json, (key, value) => {
    console.log(`key: ${key}, value: ${value}`);
    return key === 'BirthDAte' ? new Date(value) : value;
});  // json to object
console.log(obj); // { "name":"tori",  ~ etc ~ , "birthDAte":"2023~~~~" }

console.log(rabbit.birthDAte.getDate()); // o
console.log(obj.birthDAte.getDate()); // o

3. 유용한 사이트

JSON Diff checker: http://www.jsondiff.com/
JSON Beautifier/editor: https://jsonbeautifier.org/
JSON Parser: https://jsonparser.org/
JSON Validator: https://tools.learningcontainer.com/json-validator/

profile
이창목

0개의 댓글