μν°λ μ¨λ³΄λ© μ±λ¦°μ§ κ³Όμ μμ λ‘κ·ΈμΈ κΈ°λ₯ ꡬν κ³Όμ λ₯Ό μννλ©΄μ ν ν° λΆλΆμ μ€μ ν λ, stringify ν¨μλ₯Ό ν΅νμ¬ JSON νμμ λ¬Έμμ΄λ‘ λ°ννλ κ³Όμ μ΄ μμλ€. κ·Έ κ³Όμ μμ JSON ν¨μλ‘ μμ£Ό μ¬μ©νλ stringify ν¨μμ parse ν¨μμ λν΄ λͺ νν μ§κ³ λμ΄κ°κ³ μΆμλ€.
μλ°μ€ν¬λ¦½νΈ κ°μ²΄λ₯Ό JSON νμΌμ ννμ λ¬Έμμ΄λ‘ λ°ννλ ν¨μμ΄λ€.
JSON.stringify(value, replacer, space)
// value - λ³νν μλ°μ€ν¬λ¦½νΈ κ°μ²΄
// replacer - μ ν μ΅μ
μΌλ‘, ν¨μ νΉμ λ°°μ΄μ κ°μ νλ² κ±°μ³μ νμν λ΄μ©λ§μ λ°ννκ³ μ ν λ
// space - λ¬Έμμ΄λ‘ λ°νμ, 곡백μ μ¬μ©νκ³ μΆμλ μ¬μ©νλ€.
value
const obj = {name: "John", age: 30, city: "New York"};
const jsonString = JSON.stringify(obj);
console.log(jsonString); // {"name":"John","age":30,"city":"New York"}
replacer
const obj = {name: "John", age: 30, city: "New York"};
const jsonString = JSON.stringify(obj,["name"]);
// λ°°μ΄λ‘ μ€μ λ κ°λ§ μΆμΆ
console.log(jsonString);// {"name":"John"}
function replacer(key, value) {
if (typeof value === "string") {
return undefined;
}
return value;
}
const obj = {name: "John", age: 30, city: "New York"};
const jsonString = JSON.stringify(obj,replacer);
// replacer ν¨μλ₯Ό νλ² κ±°μ³μ μΆλ ₯
console.log(jsonString);// {"age":30}
space
const obj = {name: "John", age: 30, city: "New York"};
const jsonString = JSON.stringify(obj,null,5);
console.log(jsonString);
//κ²°κ³Όκ°
//{
// "name": "John",
// "age": 30,
// "city": "New York"
//}
JSON.parse(text, reviver)
// text - νμ±ν λ¬Έμμ΄
// reviver - μ€μ λ λ§€κ°λ³μ ν¨μλ νμ±ν JSON λ¬Έμμ΄μ κ° ν€/κ° μμ μ²λ¦¬νλ λ°©λ²μ μ μν©λλ€.
// μ΄ ν¨μλ νμ± κ²°κ³Ό κ°μ²΄μ κ° μμ±κ°μ λ체νκ±°λ νν°λ§νλ λ° μ¬μ©λ©λλ€.
const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // "John"
console.log(obj.age); // 30
console.log(obj.city); // "New York"