반응형

JSON.stringify(object, replacer, indent)

  • 1번째 인자: object - 변환할 객체.
  • 2번째 인자: replacer - 함수를 이용해서 필터로 사용.
                   모든 객체를 변환할 경우는 생략해도 되지만, 3번째 인자를 사용하기 위해서는 null을 입력합니다.
  • 3번째 인자: indent - 들여쓰기 space 갯수

아래 예제를 참고하세요.

첫번째 예제는 object만 변환한 예제이고,
두번째 예제는 들여쓰기는 하고 replacer는 사용하지 않은 예제, 그리고 마지막
세번째 예제는 replacer를 사용한 예제입니다.

 

( 예제1: object만 변환 )

// 객체 생성
const students = []
students.push({ 이름: '봄이', 국어: 87, 영어: 88, 수학: 89 })
students.push({ 이름: '여름이', 국어: 85, 영어: 81, 수학: 95 })
students.push({ 이름: '가을이', 국어: 67, 영어: 85, 수학: 80 })

// 출력
console.log(JSON.stringify(students))

 

( 예제1 결과 )

[{"이름":"봄이","국어":87,"영어":88,"수학":89},{"이름":"여름이","국어":85,"영어":81,"수학":95},{"이름":"가을이","국어":67,"영어":85,"수학":80}]

 

 

( 예제2: 들여쓰기는 하고 replacer는 미사용 )

// 객체 생성
const students = []
students.push({ 이름: '봄이', 국어: 87, 영어: 88, 수학: 89 })
students.push({ 이름: '여름이', 국어: 85, 영어: 81, 수학: 95 })
students.push({ 이름: '가을이', 국어: 67, 영어: 85, 수학: 80 })

// 출력
console.log(JSON.stringify(students, null, 2))

(예제2 결과)

[
  {
    "이름": "봄이",
    "국어": 87,
    "영어": 88,
    "수학": 89
  },
  {
    "이름": "여름이",
    "국어": 85,
    "영어": 81,
    "수학": 95
  },
  {
    "이름": "가을이",
    "국어": 67,
    "영어": 85,
    "수학": 80
  }
]

 

( 예제3: replacer를 사용한 예제 )

// 객체 생성
const students = []
students.push({ 이름: '봄이', 국어: 87, 영어: 88, 수학: 89 })
students.push({ 이름: '여름이', 국어: 85, 영어: 81, 수학: 95 })
students.push({ 이름: '가을이', 국어: 67, 영어: 85, 수학: 80 })

// replacer로 사용할 함수 선언
// value가 string인 key를 필터링
// 즉, 이름key의 value는 문자열이기 때문에 제외하고, 나머지 국영수 만 출력
function replacer(key, value){
  if(typeof value === 'string'){
    return undefined;
  }
  return value;
}

// 출력
console.log(JSON.stringify(students, replacer, 2))

 

( 예제3 결과 )

[
  {
    "국어": 87,
    "영어": 88,
    "수학": 89
  },
  {
    "국어": 85,
    "영어": 81,
    "수학": 95
  },
  {
    "국어": 67,
    "영어": 85,
    "수학": 80
  }
]
반응형
블로그 이미지

DeveloperN

개발자 n의 개발 이야기(draft)

,