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));
'개념 창고 > JS' 카테고리의 다른 글
[JavaScript] ==, === 비교 연산자 차이 (0) | 2024.07.30 |
---|---|
[JQuery] JQuery 기본문법 (0) | 2023.03.22 |