JSON.stringify()를 배워보자

김영진·2021년 2월 15일
0

Vanilla JavaScript_Basic

목록 보기
5/8

JSON이란?

JavaScript Object Notation의 약자로, 브라우저와 서버사이에서 오고가는 데이터의 형식

JSON.stringify(value, replacer, space);

value(필수): JSON 문자열로 변환할 값(배열, 객체, 또는 숫자, 문자 등)

replacer(선택): 함수 또는 배열이 될 수 있다. null or 제공되지 않으면, 객체의 모든 속성들이 JSON 문자열 결과에 포함된다.

  • replacer가 함수일 때
function replacer(key, value) {
  if (typeof value === ‘string’) {
    return undefined;
  }
  return value;
}
var foo = {name: ‘jason’, nickname: ‘ball’, weight: 75};
var useJson = JSON.stringify(foo, replacer); 
console.log(useJson) // {"weight":75}
  • replacer가 배열일 때
// 배열과 일치하는 값만 문자열화 된다.
var foo = {name: ‘jason’, nickname: ‘ball’, weight: 75};
var useJson = JSON.stringify(foo, [‘nickname’, ‘weight’]);
console.log(useJson); // {“nickname”:”ball”,”weight”:75}
profile
UI개발자 in Hivelab

0개의 댓글