Object to JSON
stringify(obj)
stringify는 데이터를 string타입으로 변환한다.
let json = JSON.stringify(true);
console.log(json); //"true"
let json = JSON.stringify(['Noran','Paran']);
console.log(json);
//["Noran","Paran"]
한개의 single quote가 아닌 double quote로 바뀐 것을 볼 수 있다. 이것이 JSON의 규격사항이다.
또한 아래처럼 함수나 javascript에만 자체적으로 들어있는 데이터도 JSON에 포함되지 않는다.
const coder = {
name: 'Noran',
language: 'Javascript',
height: null,
birthDate: new Date(),
symbol: Symbol('id'),
sayhi: () => {
console.log(`Hello, I'm ${name}!`);
},
};
let json = JSON.stringify(coder);
console.log(json);
//{"name":"Noran","language":"Javascript","height":null,"birthDate":"2022-06-29T03:38:30.798Z"}
내가 원하는 property만 골라서 JSON으로 전달할 수 있다.
let json = JSON.stringify(coder, ['name','language']);
console.log(json);
// {"name":"Noran","language":"Javascript"}
조금더 세밀하게 통제하고 싶을 때 아래처럼 콜백함수를 사용할 수 있다.
json = JSON.stringify(coder, (key, value) => {
console.log(`key: ${key}, value: ${value}`);
return value;
});
console.log(json);
// key: , value: [object Object]
// key: name, value: Noran
// key: language, value: Javascript
// key: height, value: null
// key: birthDate, value: 2022-06-29T03:46:52.806Z
// key: sayhi, value: () => {
// console.log(`Hello, I'm ${name}!`);
// }
// {"name":"Noran","language":"Javascript","height":null,"birthDate":"2022-06-29T03:46:52.806Z"}
json = JSON.stringify(coder, (key, value) => {
console.log(`key: ${key}, value: ${value}`);
return key ==='name'?'Paran' : value;
});
console.log(json);
// key: , value: [object Object]
// key: name, value: Noran
// key: language, value: Javascript
// key: height, value: null
// key: birthDate, value: 2022-06-29T03:49:50.917Z
// key: sayhi, value: () => {
// console.log(`Hello, I'm ${name}!`);
// }
// {"name":"Paran","language":"Javascript","height":null,"birthDate":"2022-06-29T03:49:50.917Z"}
출처 : 드림코딩 https://www.youtube.com/@dream-coding / MDN https://developer.mozilla.org/ko
'🟨 JavaScript > 개념' 카테고리의 다른 글
| [mdn, 드림코딩, 코딩애플] 콜백함수 (1) : 동기와 비동기 개념 (0) | 2022.07.12 |
|---|---|
| [드림코딩] JSON to Object (parse) (0) | 2022.07.12 |
| [드림코딩] JSON이란? (0) | 2022.06.29 |
| [드림코딩] 유용한 배열(array) api (3) : reduce, reduceRight, sort, api 다중으로 쓰기 (0) | 2022.06.15 |
| [드림코딩] 유용한 배열(array) api (2) : filter, map, some, every (0) | 2022.06.09 |