상세 컨텐츠

본문 제목

JSON.stringify()

JavaScript

by 폴리프레임 2024. 7. 5. 13:59

본문

반응형

JSON.stringify() 함수는 JavaScript 객체나 배열을 JSON 문자열로 변환할 때 사용됩니다. 이 함수는 객체나 배열을 네트워크 전송, 데이터 저장, 로그 기록 등의 목적으로 문자열로 변환하는 데 매우 유용합니다.

  1. 데이터 전송: Fetch API 등를 사용하여 서버로 데이터를 전송할 때 객체를 JSON 문자열로 변환하여 전송합니다.
  2. 데이터 저장: 로컬 스토리지 또는 세션 스토리지에 객체를 저장할 때 JSON 문자열로 변환하여 저장합니다.
  3. 로그 기록: 디버깅을 위해 객체의 상태를 문자열 형태로 기록하거나 콘솔에 출력할 때 사용합니다.
  4. 객체를 파일 시스템에 저장하거나 다른 프로그램에서 읽을 수 있는 형태로 변환할 때 사용합니다.

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자리로 한다.

 

'JavaScript' 카테고리의 다른 글

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

관련글 더보기