🌈 JavaScript
JSON.stringify
James Wetzel
2023. 8. 10. 11:44
728x90
반응형
JSON은 "JavaScript Object Notation"의 약자로, 데이터 교환을 위해 사용되는 경량의 데이터 형식입니다.
JSON.stringify(value[, replacer[, space]])
const person = {
name: "John",
age: 30,
city: "New York"
};
const jsonString = JSON.stringify(person);
console.log(jsonString);
{"name":"John","age":30,"city":"New York"}
// replacer 옵션과 space 옵션 사용 예제
const person = {
name: "John",
age: 30,
city: "New York",
sensitiveInfo: "This should be hidden"
};
// replacer 함수를 사용하여 sensitiveInfo 속성을 필터링하고 변환
const filteredJSON = JSON.stringify(person, (key, value) => {
if (key === "sensitiveInfo") {
return undefined; // 해당 속성은 무시됨
}
return value;
}, 2); // 2개의 공백 문자로 들여쓰기
console.log("Filtered JSON:");
console.log(filteredJSON);
// space 옵션을 사용하여 가독성을 높인 JSON 문자열 생성
const formattedJSON = JSON.stringify(person, null, 4); // 4개의 공백 문자로 들여쓰기
console.log("\nFormatted JSON:");
console.log(formattedJSON);
Filtered JSON:
{
"name": "John",
"age": 30,
"city": "New York"
}
Formatted JSON:
{
"name": "John",
"age": 30,
"city": "New York",
"sensitiveInfo": "This should be hidden"
}
728x90
반응형