개념 창고/JS

JSON.stringify(value, replacer, space) 설명

달마루 2024. 8. 8. 10:06

JSON.stringify(value, replacer, space)
메서드는 JavaScript 객체를 JSON 문자열로 변환할 때 사용된다.

value: JSON 문자열로 변환할 객체.
replacer: 포함할 속성을 정의하거나 속성을 변환하는 함수 또는 배열.
space: 반환된 JSON 문자열의 가독성을 높이기 위한 공백 또는 문자열 (들여쓰기). 

const obj = { name: "Alice", age: 30, city: "Wonderland", password: "secret" };

// replacer 함수: 'password' 속성을 제외
function replacer(key, value) {
  if (key === "password") {
    return undefined;
  }
  return value;
}

// space 매개변수: 들여쓰기를 사용하여 포맷
const jsonString = JSON.stringify(obj, replacer, 4);
console.log(jsonString);
/* 출력:
{
    "name": "Alice",
    "age": 30,
    "city": "Wonderland"
}
*/

 

PS. Json 타입으로 로그 출력도 가능하다.

console.log(JSON.stringify(myJsonData, null, 2));