๊ฐ์ด๋ ๊ฐ์ฒด๋ฅผ ๋ํ๋ด์ฃผ๋ ๋ฒ์ฉ ํฌ๋งท
JavaScript ๊ฐ์ด๋ ๊ฐ์ฒด๋ฅผ JSON ๋ฌธ์์ด๋ก ๋ณํํด์ค๋ค.
let student = {
name: 'John',
age: 30,
isAdmin: false,
courses: ['html', 'css', 'js'],
wife: null
};
let json = JSON.stringify(student);
alert(typeof json); // ๋ฌธ์์ด์ด๋ค์!
alert(json);
/* JSON์ผ๋ก ์ธ์ฝ๋ฉ๋ ๊ฐ์ฒด:
{
"name": "John",
"age": 30,
"isAdmin": false,
"courses": ["html", "css", "js"],
"wife": null
}
*/
console.log(JSON.stringify({ x: 5, y: 6 }));
// expected output: "{"x":5,"y":6}"
console.log(JSON.stringify([new Number(3), new String('false'), new Boolean(false)]));
// expected output: "[3,"false",false]"
console.log(JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] }));
// expected output: "{"x":[10,null,null,null]}"
console.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)));
// expected output: ""2006-01-02T15:04:05.000Z""
JSON ๋ฌธ์์ด์ ๊ตฌ๋ฌธ์ ๋ถ์ํ๊ณ , ๊ทธ ๊ฒฐ๊ณผ์์ JavaScript ๊ฐ์ด๋ ๊ฐ์ฒด๋ฅผ ์์ฑํ๋ค.
์ฆ, JSON์ผ๋ก ์ธ์ฝ๋ฉ๋ ๊ฐ์ฒด๋ฅผ ๋ค์ ๊ฐ์ฒด๋ก ๋์ฝ๋ฉ ํด์ค๋ค.
// ๋ฌธ์์ด๋ก ๋ณํ๋ ๋ฐฐ์ด
let numbers = "[0, 1, 2, 3]";
numbers = JSON.parse(numbers);
alert( numbers[1] ); // 1
localStorage์ array(๋ฐฐ์ด)๋ ์ ์ฅ๋์ง ์๋๋ค.
์ด๋ JSON.stringify()
๋ฅผ ์ฌ์ฉํ์ฌ array์ ์ ์ฌํ string์ผ๋ก ์ ์ฅํ ์ ์๋ค.
์ด array์ ์ ์ฌํ string์ ์ง์ง array๋ก ๋ณํํ๋ ค๋ฉด JSON.parse()
๋ฅผ ์ฌ์ฉํ๋ฉด ๋๋ค.