JSON.stringify () 기능

JSON.stringify를 간단히 JSON문자열로 변환할때만 사용할 때 썼었는데, 몰랐던 기능들이 있습니다.

 

 

1. 찾고자하는 키 값을 두번째 인수에 넣어 전달하면 원하는 키의 배열만 리턴받을 수 있다.

{"id":"0001","type":"donut","name":"Cake","ppu":0.55,"batters":{"batter":[{"id":"1001","type":"Regular"},{"id":"1002","type":"Chocolate"},{"id":"1003","type":"Blueberry"},{"id":"1004","type":"Devil’s Food"}]},"topping":[{"id":"5001","type":"None"},{"id":"5002","type":"Glazed"},{"id":"5005","type":"Sugar"},{"id":"5007","type":"Powdered Sugar"},{"id":"5006","type":"Chocolate with Sprinkles"},{"id":"5003","type":"Chocolate"},{"id":"5004","type":"Maple"}]}

console.log(JSON.stringify(product,['name']);

// RESULT
{"name" : "Cake"}

 

 

2. 두번째 인수에 함수를 넣어 원하는 값을 리턴 받을 수 있다.

undefined일 경우에는 리턴되지 않는다.

const user = {
	"name" : "Prateek Singh",
	"age" : 26
}

JSON.stringfy(user, (key, value) => {     
	if(typeof value == 'string'){
        return undefined;
    }
    return value;
});

// RESULT
{ "age": 26}

 

 

3. 세번째 인수가 '숫자'일 경우 문자열의 간격을 제어할 수 있다.

4. 세번째 인수가 '문자'일 경우 공백 대신 문자를 삽입할 수 있다.

 

 

5. toJson

키값에 따라 객체를 바로 리턴하지 않고 메서드를 통해 원하는 키 값을 합쳐서 반환할 수 있다.

const user = {
	firstName : "Prateek",
    lastName : "Singh",
    age : 26,
    toJSON() {
    	return {
        	fullName: `${this.firstName} + ${this.lastName}`
        };
	}
}

console.log(JSON.stringify(user));

// RESULT
"{ "fullName" : "Prateek Singh"}"

 


원본, 코드 출처

https://medium.com/javascript-in-plain-english/5-secret-features-of-json-stringify-c699340f9f27

 

+ Recent posts