JS) JSON.stringify(), JSON.parse()

Ceciliaยท2022๋…„ 12์›” 20์ผ
0

JavaScript

๋ชฉ๋ก ๋ณด๊ธฐ
22/36
post-thumbnail

https://ko.javascript.info/json




๐Ÿ” JSON (JavaScript Object Notation)


๊ฐ’์ด๋‚˜ ๊ฐ์ฒด๋ฅผ ๋‚˜ํƒ€๋‚ด์ฃผ๋Š” ๋ฒ”์šฉ ํฌ๋งท




JSON.stringify()


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.parse()


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()๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

profile
'์ด๊ฒŒ ์ตœ์„ ์ผ๊นŒ?'๋ผ๋Š” ๊ณ ์ฐฐ์„ ํ†ตํ•ด ๋์—†์ด ์„ฑ์žฅํ•˜๊ณ , ๊ทธ ๊ณผ์ •์„ ์ฆ๊ธฐ๋Š” ํ”„๋ก ํŠธ์—”๋“œ ๊ฐœ๋ฐœ์ž์ž…๋‹ˆ๋‹ค. ์‚ฌ์šฉ์ž์˜ ์ž…์žฅ์„ ์ƒ๊ฐํ•˜๋ฉฐ ์ตœ์„ ์˜ ํŽธ์˜์„ฑ์„ ์ฐพ๊ธฐ ์œ„ํ•ด ๋…ธ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€