Jieunny์˜ ๋ธ”๋กœ๊ทธ

S3) Unit 1. [์ž๋ฃŒ๊ตฌ์กฐ/์•Œ๊ณ ๋ฆฌ์ฆ˜] JSON.stringify ๋ณธ๋ฌธ

CodeStates/learning contents

S3) Unit 1. [์ž๋ฃŒ๊ตฌ์กฐ/์•Œ๊ณ ๋ฆฌ์ฆ˜] JSON.stringify

Jieunny 2023. 2. 14. 11:00

๐Ÿ“ฃ JSON์˜ ํƒ„์ƒ ๋ฐฐ๊ฒฝ

โœ”๏ธ JSON : JavaScript Object Notation

โžฐ ๋ฐ์ดํ„ฐ ๊ตํ™˜์„ ์œ„ํ•ด ๋งŒ๋“ค์–ด์ง„ ๊ฐ์ฒด ํ˜•ํƒœ์˜ ํฌ๋งท

 

โžฐ ๋ฐ์ดํ„ฐ๋ฅผ ์ „์†ก ๊ฐ€๋Šฅํ•œ ์กฐ๊ฑด

    ๏น’ ์ˆ˜์‹ ์ž์™€ ๋ฐœ์‹ ์ž๊ฐ€ ๊ฐ™์€ ํ”„๋กœ๊ทธ๋žจ์„ ์‚ฌ์šฉํ•œ๋‹ค.

    ๏น’ ๋˜๋Š”, ๋ฌธ์ž์—ด์ฒ˜๋Ÿผ ๋ฒ”์šฉ์ ์œผ๋กœ ์ฝ์„ ์ˆ˜ ์žˆ์–ด์•ผ ํ•œ๋‹ค.

 

โžฐ ๊ฐ์ฒด๋Š” ํƒ€์ž… ๋ณ€ํ™˜์„ ์ด์šฉํ•ด String์œผ๋กœ ๋ณ€ํ™˜ํ•  ๊ฒฝ์šฐ ๊ฐ์ฒด ๋‚ด์šฉ์„ ํฌํ•จํ•˜์ง€ ์•Š๋Š”๋‹ค -> JS์—์„œ ๊ฐ์ฒด๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ํ•˜๊ธฐ ์œ„ํ•ด ๋ฉ”์„œ๋“œ .toString()์ด๋‚˜ String(str)์„ ์‚ฌ์šฉํ•˜๋ฉด [object Object] ๋ผ๋Š” ๊ฒฐ๊ณผ๋ฅผ ๋ฆฌํ„ดํ•œ๋‹ค.

 

โžฐ ์ด๋ฅผ ํ•ด๊ฒฐํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ๊ฐ์ฒด๋ฅผ JSON์˜ ํ˜•ํƒœ๋กœ ๋ณ€ํ™˜ํ•˜๊ฑฐ๋‚˜ JSON์„ ๊ฐ์ฒด์˜ ํ˜•ํƒœ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

    ๏น’ JSON.stringiify : ๊ฐ์ฒด๋ฅผ JSON์œผ๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค(์ง๋ ฌํ™”)

    ๏น’ JSON.parse: JSON์„ ๊ฐ์ฒด๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค(์—ญ์ง๋ ฌํ™”)

    ๐Ÿšจ JSON์œผ๋กœ ๋ณ€ํ™˜๋œ ๊ฐ์ฒด์˜ ํƒ€์ž…์€ '๋ฌธ์ž์—ด' ์ด๋‹ค.

 

โžฐ ๊ฐ์ฒด๋ฅผ JSON์œผ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ๋ฉ”์„œ๋“œ JSON.stringify

let transferableMessage = JSON.stringify(message)

console.log(transferableMessage) 
// `{"sender":"๊น€์ฝ”๋”ฉ","receiver":"๋ฐ•ํ•ด์ปค","message":"ํ•ด์ปค์•ผ ์˜ค๋Š˜ ์ €๋… ๊ฐ™์ด ๋จน์„๋ž˜?","createdAt":"2021-01-12 10:10:10"}`

console.log(typeof(transferableMessage))
// `string`

 

โžฐ ์ง๋ ฌํ™”๋œ JSON์— ๋ฉ”์„œ๋“œ JSON.parse๋ฅผ ์ ์šฉํ•ด์„œ ๋‹ค์‹œ ๊ฐ์ฒด์˜ ํ˜•ํƒœ๋กœ ๋ณ€ํ™˜ํ•˜๊ธฐ

let packet = `{"sender":"๊น€์ฝ”๋”ฉ","receiver":"๋ฐ•ํ•ด์ปค","message":"ํ•ด์ปค์•ผ ์˜ค๋Š˜ ์ €๋… ๊ฐ™์ด ๋จน์„๋ž˜?","createdAt":"2021-01-12 10:10:10"}`
let obj = JSON.parse(packet)

console.log(obj)
/*
 * {
 * sender: "๊น€์ฝ”๋”ฉ",
 * receiver: "๋ฐ•ํ•ด์ปค",
 * message: "ํ•ด์ปค์•ผ ์˜ค๋Š˜ ์ €๋… ๊ฐ™์ด ๋จน์„๋ž˜?",
 * createdAt: "2021-01-12 10:10:10"
 * }
 */

 console.log(typeof(obj))
 // `object`

 

๐Ÿ“ฃ JSON์˜ ๊ธฐ๋ณธ ๊ทœ์น™

  ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๊ฐ์ฒด JSON
ํ‚ค ๋”ฐ์˜ดํ‘œ ์—†์ด ์“ธ ์ˆ˜ ์žˆ๋‹ค.
{ key : "property" }
๋ฐ˜๋“œ์‹œ ์Œ๋”ฐ์˜ดํ‘œ๋ฅผ ๋ถ™์—ฌ์•ผ ํ•œ๋‹ค.
'{ "key" : "property" }'
๋ฌธ์ž์—ด ๊ฐ’ ์ž‘์€ ๋”ฐ์˜ดํ‘œ๋„ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•˜๋‹ค.
{ "key" : 'property' }
๋ฐ˜๋“œ์‹œ ํฐ๋”ฐ์˜ดํ‘œ๋กœ ๊ฐ์‹ธ์•ผ ํ•œ๋‹ค.
'{"key":"property"}'
ํ‚ค์™€ ๊ฐ’ ์‚ฌ์ด ๊ณต๋ฐฑ ์‚ฌ์šฉ ๊ฐ€๋Šฅ
{"key" : 'property'}
์‚ฌ์šฉ ๋ถˆ๊ฐ€๋Šฅ
'{"key":"property"}'
ํ‚ค-๊ฐ’ ์Œ ์‚ฌ์ด ๊ณต๋ฐฑ ์‚ฌ์šฉ ๊ฐ€๋Šฅ
{ "key":'property', num:1 }
์‚ฌ์šฉ ๋ถˆ๊ฐ€๋Šฅ
'{"key":"property","num":1}'