코드스테이츠 프론트엔드 부트캠프-Section3 JSON Stringify를 재귀함수로?

그래도 아무튼 개발자·2023년 4월 12일
0

Front_End

목록 보기
10/12
post-thumbnail

브라우저에는 JSON.Stringify 라는 함수가 존재한다.

객체 -> JSON

쉽게 표현하면 위와 같다. 객체로 되어있는 형태를 JSON의 형태로 변환하는 것!

예를 들면

const message = {
  sender: "김코딩",
  receiver: "박해커",
  message: "해커야 오늘 저녁 같이 먹을래?"
}

let transferableMessage = JSON.stringify(message)

console.log(transferableMessage) 
// `{"sender":"김코딩","receiver":"박해커","message":"해커야 오늘 저녁 같이 먹을래?"}`

console.log(typeof(transferableMessage))
// `string`

객체 형태였던 message가 JSON 형태로 변경되면서 직렬화가 된 것을 알 수 있다.

어찌되었든 객체 형태가 JSON 형태로 바뀐다.. 이 둘의 형태가 어떻게 다른걸까?

미묘하게 차이가 있다. 또 '반드시'라고 들어가는 조건들이 보인다.

이러한 stringify 함수를 재귀함수로 구현해보자!

function stringifyJSON(obj) {
  if(typeof obj === 'function') return ``;	// function일 경우 빈 문자열
  else if(obj === undefined) return ``;	// undefined일 경우 빈 문자열
  else if(typeof obj === 'number') return `${obj}`;	
  else if(obj === null) return `null`;
  else if(typeof obj === 'boolean') return `${obj}`;
  else if(typeof obj === 'string') return `"${obj}"`;	//string(문자열)은 큰따옴표 추가!
  else if(Array.isArray(obj)) {		//배열일 경우
    for(let i=0; i<obj.length; i++) {
      obj[i] = stringifyJSON(obj[i]);	//모든 요소들을 재귀함수를 호출하여 변환
    }
    return '[' + obj.join() + ']';	//join으로 묶어버리기
  }
  else if(typeof obj === 'object') {	//객체일 경우
    let result='';	//공백 선언
    let keys=Object.keys(obj);	//key만 들어있는 배열
    for(let el in obj) {
      if(typeof obj[el] === 'function' || obj[el] === undefined) result += ``;	//value값이 function이거나 undefined일 경우 공백으로 설정
      else {
        result += stringifyJSON(el) + ':' + stringifyJSON(obj[el]);	//key값 value값 모두 재귀함수를 호출하여 변환
        if(String(el) !== keys[keys.length-1]) result += ','	//현재 반복문의서의 el값이 객체 key값들 중 마지막 요소인지 아닌지 여부 판단
      }
    }
    return ('{' + result + '}');
  }
};

풀고 나서 레퍼런스를 보면 약간 다르게 풀긴 했지만 나름 만족 🫡🫡

0개의 댓글