티스토리 뷰

🌈 JavaScript

JSON.stringify

James Wetzel 2023. 8. 10. 11:44

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"
}
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함