JSON.stringify() 함수는 JavaScript 객체나 배열을 JSON 문자열로 변환할 때 사용됩니다. 이 함수는 객체나 배열을 네트워크 전송, 데이터 저장, 로그 기록 등의 목적으로 문자열로 변환하는 데 매우 유용합니다.
3가지 유형
JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)
1. JSON.stringify( 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"}'
// 배열의 경우
const arr = [1, 2, 3, "four", "five"];
const jsonString = JSON.stringify(arr);
console.log(jsonString); // '[1,2,3,"four","five"]'
console.log(typeof jsonString); // string
console.log(typeof arr); // object
console.log(Array.isArray(arr)) // true
console.log(JSON.stringify({ x: 5, y: 6 })); // '{"x":5,"y":6}'
console.log(
JSON.stringify([new Number(3), new String('false'), new Boolean(false)]),
); // '[3,"false",false]'
2. JSON.stringify( value, replacer )
// replacer 함수
const obj = {
name: "John",
age: 30,
city: "New York"
};
const jsonStringWithReplacer = JSON.stringify(obj, (key, value) => {
if (typeof value === "string") {
return undefined; // 문자열 값을 필터링
}
return value;
});
console.log(jsonStringWithReplacer); // '{"age":30}'
3. JSON.stringify( obj, null ,2)
위의 예제의 obj객체를 표기 할때, 인덴트(들여쓰기)를 2자리로 한다.
| json() 과 JSON.parse() (2) | 2024.07.05 |
|---|---|
| forEach() - advanced (1) | 2024.07.05 |
| clsx, twMerge, cn, shadcn-ui (0) | 2024.07.05 |
| toJSON(), JSON.stringify() (1) | 2024.06.18 |
| .at() (0) | 2024.06.18 |