JSON

heyj·2022년 1월 24일
0

HTML/CSS/Javascript

목록 보기
3/8
post-thumbnail

Object to JSON : stringfy(object)

let json = JSON.stringfy(true);
console.log(json) // true

json = JSON.stringfy(['baseball', 'soccer']);
console.log(json) // ['baseball', soccer']

const dog = {
	name: 'toto',
    color: 'black',
    size: null,
	}
    
json = JSON.stringfy(dog, ["name"])
console.log(json) // {"name": "toto"}

json = JSON.stringfy(dog, (key, value) => {
	console.log(`key: ${key}, value: ${value}`);
    return key === 'name' ? 'john' : value;
})

console.log(json)
// {"name":"john", "color":"black", "size":null}

JSON to Object : parse(JSON)

const dog = {
	name: 'toto',
    color: 'black',
    size: null,
    birthday: Date.now()
	}

json = JSON.stringify(dog);
const object = JSON.parse(json, (key, value) => {
  console.log(`key: ${key}, value: ${value}`);
  return key === "birthday" ? new Date(value) : value;
});
console.log("json to object:", obj);
// json to object: {
  name: 'tori',
  color: 'white',
  size: null,
  birthday: 2021-12-24T13:37:47.139Z
}



0개의 댓글