JSON

์œ ์•„ํ˜„ยท2022๋…„ 12์›” 16์ผ
0

๊ธฐ๋ก

๋ชฉ๋ก ๋ณด๊ธฐ
2/29
post-thumbnail

โค๏ธโ€๐Ÿ”ฅ JSON

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

๐Ÿค” ๋„คํŠธ์›Œํฌ๋ฅผ ํ†ตํ•ด์„œ ์–ด๋–ค ๊ฐ์ฒด์˜ ๋‚ด์šฉ์„ ๋‹ค๋ฅธ ํ”„๋กœ๊ทธ๋žจ์— ์ „์†กํ•œ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด ๋ณด์ž.

  • ๊ฐ์ฒด์˜ ๋‚ด์šฉ์„ ์ผ์ข…์˜ ๋ฉ”์‹ ์ €, ์ฑ„ํŒ… ํ”„๋กœ๊ทธ๋žจ์—์„œ ์“ฐ๋Š” ํ•˜๋‚˜์˜ ๋ฉ”์‹œ์ง€๋ผ๊ณ  ํ•œ๋‹ค๋ฉด, ์ด ๊ฐ์ฒด๋ฅผ ์–ด๋–ป๊ฒŒ ์ „์†กํ•  ์ˆ˜ ์žˆ์„๊นŒ?
const message = {
  sender: "๊น€์ฝ”๋”ฉ",
  receiver: "๋ฐ•ํ•ด์ปค",
  message: "ํ•ด์ปค์•ผ ์˜ค๋Š˜ ์ €๋… ๊ฐ™์ด ๋จน์„๋ž˜?",
  createdAt: "2022-12-15 10:10:10"
}
  • ๋ฉ”์‹œ์ง€ ๊ฐ์ฒด๋ฅผ ์ „์†กํ•˜๋ ค๋ฉด ์กฐ๊ฑด์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.
[์ „์†ก ๊ฐ€๋Šฅํ•œ ์กฐ๊ฑด]
1. ์ˆ˜์‹ ์ž์™€ ๋ฐœ์‹ ์ž๊ฐ€ ๊ฐ™์€ ํ”„๋กœ๊ทธ๋žจ์„ ์‚ฌ์šฉํ•œ๋‹ค.
2. ๋ฌธ์ž์—ด์ฒ˜๋Ÿผ ๋ฒ”์šฉ์ ์œผ๋กœ ์ฝ์„ ์ˆ˜ ์žˆ์–ด์•ผ ํ•œ๋‹ค.
  • ๊ฐ์ฒด๋Š” ํƒ€์ž… ๋ณ€ํ™˜์„ ์ด์šฉํ•ด String์œผ๋กœ ๋ณ€ํ™˜ํ•  ๊ฒฝ์šฐ์— ๊ฐ์ฒด์— ๋‚ด์šฉ์„ ํฌํ•จํ•˜์ง€ ์•Š๋Š”๋‹ค. JavaScript์—์„œ ๊ฐ์ฒด๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ํ•˜๊ธฐ ์œ„ํ•ด์„œ ๋ฉ”์„œ๋“œ message.toString() ์ด๋‚˜
    ํ˜•๋ณ€ํ™˜ String(message) ์„ ์‹œ๋„ํ•˜๊ฒŒ ๋  ๋•Œ, [object Object] ๋ผ๋Š” ๊ฒฐ๊ณผ๋ฅผ ๋ฆฌํ„ดํ•œ๋‹ค. ์ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด ๊ฐ์ฒด๋ฅผ JSON์˜ ํ˜•ํƒœ๋กœ ๋ณ€ํ™˜ํ•˜๊ฑฐ๋‚˜ JSON์„ ๊ฐ์ฒด ํ˜•ํƒœ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค.
[๊ฐ์ฒด๋ฅผ JSON์œผ๋กœ ๋ณ€ํ™˜] => JSON>stringfy
let transferableMessage = JSON.stringify(message)

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

console.log(typeof(transferableMessage))
// `string`
  • ์œ„์™€ ๊ฐ™์ด ๊ฐ์ฒด๋ฅผ JSON.stringfyํ•˜๋Š” ๊ณผ์ •์„ ์ง๋ ฌํ™” ํ•œ๋‹ค๊ณ  ํ•œ๋‹ค. ์ง๋ ฌํ™”ํ•œ transferableMessage ์˜ ํƒ€์ž…์€ string ์ด๋ฉฐ ๊ฐ์ฒด๋ฅผ ์ง๋ ฌํ™”ํ•œ ์ด ๋ฌธ์ž์—ด์„ ๋ˆ„๊ตฐ๊ฐ€์—๊ฒŒ ๋ณด๋‚ผ ์ˆ˜ ์žˆ๋‹ค. JSON.stringify ์™€ ์ •๋ฐ˜๋Œ€์˜ ์ž‘์—…์„ ์ˆ˜ํ–‰์„ ํ•˜๋Š” ๋ฉ”์„œ๋“œ JSON.parse ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.
[JSON์„ ๊ฐ์ฒด๋กœ ๋ณ€ํ™˜] => JSON.parse

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

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

 console.log(typeof(obj))
 // `object`
 
  • ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ง๋ ฌํ™”ํ•œ string ํ˜•ํƒœ์˜ ๋ฉ”์‹œ์ง€๋ฅผ ๋‹ค์‹œ parse๋ฅผ ํ†ตํ•ด ๊ฐ์ฒด ํ˜•ํƒœ๋กœ ๋ณ€ํ™˜์‹œ์ผœ์ฃผ๋Š” ๊ณผ์ •์„ ์—ญ์ง๋ ฌํ™” ๋ผ๊ณ  ํ•œ๋‹ค. ์ด์ฒ˜๋Ÿผ JSON์€ ์„œ๋กœ ๋‹ค๋ฅธ ํ”„๋กœ๊ทธ๋žจ ์‚ฌ์ด์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๊ตํ™˜ํ•˜๊ธฐ ์œ„ํ•œ ํฌ๋งท์œผ๋กœ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋ฅผ ํฌํ•จํ•œ ๋งŽ์€ ์–ธ์–ด์—์„œ ๋ฒ”์šฉ์ ์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ์œ ๋ช…ํ•œ ํฌ๋งท์ด๋‹ค.

โ—JSON์˜ ๊ธฐ๋ณธ ๊ทœ์น™

  • JSON์€ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์˜ ๊ฐ์ฒด์™€ ๋‹ค๋ฅผ ๊ฒŒ ์—†์–ด ๋ณด์ด์ง€๋งŒ, ๋ฏธ๋ฌ˜ํ•˜๊ฒŒ ๋‹ค๋ฅธ ๊ทœ์น™์ด ์กด์žฌํ•œ๋‹ค.

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