๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“Œ Language/Javascript

[JS] JSON๊ณผ ๊ฐ์ฒด ๋‹ค๋ฃจ๊ธฐ

by Fomagran ๐Ÿ’ป 2022. 2. 5.
728x90
๋ฐ˜์‘ํ˜•

์•ˆ๋…•ํ•˜์„ธ์š” Foma ๐Ÿ’ป ์ž…๋‹ˆ๋‹ค!

 

์˜ค๋Š˜์€ JavaScript๋กœ JSON๊ณผ ๊ฐ์ฒด๋ฅผ ๋‹ค๋ฃจ๋Š” ๋ฒ•์— ๋Œ€ํ•ด์„œ ์ •๋ฆฌํ•ด ๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

 

๋ฐ”๋กœ ์‹œ์ž‘ํ• ๊ฒŒ์š”~


๊ฐ์ฒด๋ฅผ JSON์œผ๋กœ ๋ฐ”๊พธ๊ธฐ

 

JSON.stringify(๊ฐ์ฒด) ๊ตฌ๋ฌธ์„ ์‚ฌ์šฉํ•˜์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

 

let user = {
    name:"foma",
    age:27,
    color:"Black",
    [Symbol("id")]:123
}
let json = JSON.stringify(user)
console.log(json) //{"name":"foma","age":27,"color":"Black"}

 

๋งŒ์•ฝ ๋ฉ”์„œ๋“œ๋‚˜ undefined๊ฐ’์„ ๊ฐ€์ง„ ํ”„๋กœํผํ‹ฐ๊ฐ€ ์žˆ๋‹ค๋ฉด ์ž๋™์œผ๋กœ ๋ฌด์‹œํ•ฉ๋‹ˆ๋‹ค.

 

user.sayHi = function() {
    print("sayHi")
}
user.somthing = undefined
let json = JSON.stringify(user)
console.log(json) //{"name":"foma","age":27,"color":"Black"}

 

์ค‘์ฒฉ๋œ ๊ฐ์ฒด๋„ ์•Œ์•„์„œ ๋ฐ”๊ฟ”์ค๋‹ˆ๋‹ค.

 

user.family =  {
    father:"KS",
    mother:"MR"
}
let json = JSON.stringify(user)
console.log(json) //{"name":"foma","age":27,"color":"Black","family":{"father":"KS","mother":"MR"}}

 

์ฃผ์˜ํ•˜์‹ค ์ ์€ ์•„๋ž˜์™€ ๊ฐ™์ด ์ˆœํ™˜์ฐธ์กฐ๊ฐ€ ์žˆ๋‹ค๋ฉด ์—๋Ÿฌ๊ฐ€ ๋‚ฉ๋‹ˆ๋‹ค.

 

let room = {
    number:92
}
room.user = user
user.room = room
//์—๋Ÿฌ
console.log(JSON.stringify(user))

 

์›ํ•˜๋Š” ํ”„๋กœํผํ‹ฐ๋งŒ ์ธ์ฝ”๋”ฉํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ๋‘ ๊ฐ€์ง€๊ฐ€ ์žˆ๋Š”๋ฐ์š”.

 

์ฒซ ๋ฒˆ์งธ๋Š” ์›ํ•˜๋Š” ํ”„๋กœํผํ‹ฐ๋ฅผ ์ง€์ •ํ•ด์ฃผ๋Š” ๋ฐฉ๋ฒ•์ด๊ณ ,

 

console.log((JSON.stringify(user,['name','age'])) //{"name":"foma","age":27}

 

๋‘ ๋ฒˆ์งธ๋Š” ์›ํ•˜์ง€ ์•Š๋Š” ํ”„๋กœํผํ‹ฐ๋ฅผ ๋นผ๋Š” ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค.

 

return key == "๋นผ๊ณ ์‹ถ์€ ํ”„๋กœํผํ‹ฐ๋ช…" ์„ ๋„ฃ์œผ์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

 

let json = JSON.stringify(user,function replacer(key,value) {
    return (key == "name") ? undefined : value
}) 

console.log(json) //{"age":27,"color":"Black","family":{"father":"KS","mother":"MR"}}

 

JSON.stringify(value,replacer,space)์—์„œ space์— ๊ฐ’์„ ๋„ฃ์–ด์ค˜ ๊ฐ€๋…์„ฑ์„ ๋†’์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

print(JSON.stringify(user,null,2))
/*{
  "name": "foma",
  "age": 27,
  "color": "Black",
  "family": {
    "father": "KS",
    "mother": "MR"
  }
}
*/

JSON์„ ๊ฐ์ฒด๋กœ ๋งŒ๋“ค๊ธฐ(Parsing)

 

JSON.parse("JSON๋ฌธ์ž์—ด") ๊ตฌ๋ฌธ์„ ์ด์šฉํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

 

let parse = JSON.parse(json)
print(parse.name) //"foma"

 

๋งŒ์•ฝ ๋‚ ์งœ๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๊ฒƒ์ด ์žˆ๋‹ค๋ฉด ๊ฐ์ฒด๋กœ ๋ฐ”๊ฟ€ ๋•Œ Date๋กœ ๋ฐ”๊ฟ”์ค˜์•ผ๊ฒ ์ฃ ?

 

์•„๋ž˜์™€ ๊ฐ™์ด ํŠน์ • ํ”„๋กœํผํ‹ฐ๋งŒ ์›ํ•˜๋Š” ์ž๋ฃŒํ˜•์œผ๋กœ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

let parse1 = JSON.parse(json,function(key,value) {
    if (key == "createdDate") {
        return new Date(value)
    }else {
        return value
    }
})
print(parse1.createdDate.getDate()) //4

Reference

 

 

๋ชจ๋˜ JavaScript ํŠœํ† ๋ฆฌ์–ผ

 

ko.javascript.info

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€