์๋ ํ์ธ์ 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
'๐ Language > Javascript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JS] ํด๋์ค(Class) ๊ธฐ๋ณธ ๋ฌธ๋ฒ๊ณผ ์์ (0) | 2022.02.12 |
---|---|
[JS] ํ๋กํ ํ์ (Prototype) ๋ค๋ค๋ณด๊ธฐ (0) | 2022.02.12 |
[JS] ํ๋กํผํฐ ์ต์ (ํ๋๊ทธ) ๋ค๋ฃจ๊ธฐ(Property Flag) (0) | 2022.02.12 |
[JS] ๊ตฌ์กฐ๋ถํด(Destructuring) (feat. ์ฝ๊ฒ ๋ณ์ ๋ง๋ค๊ธฐ) (0) | 2022.02.05 |
[JS] iOS ๊ฐ๋ฐ์๊ฐ ์ดํดํ๋ JavaScript ๊ธฐ์ด๋ฌธ๋ฒ (feat. Swift) (0) | 2022.02.05 |
๋๊ธ