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 |