[06.12] JSON.stringify

0
post-thumbnail

목차

  • JSON
  • JSON.stringify 과제
  • Tree UI 과제

📌 JSON

: JSON(Javascript Object Notation)의 줄임말로 데이터 교환을 위해 만들어진 객체 형태의 포맷

JSON.stringify와 JSON.parse

  • JSON.stringify : 객체를 JSON으로 변환 (직렬화)
    - JSON으로 변환된 객체의 타입은 "문자열"
let transferableMessage = JSON.stringify(message)

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

console.log(typeof(transferableMessage))
// `string`
  • JSON.parse : JSON을 객체로 변환 (역직렬화)
    - 문자열을 객체의 형태로 변환함
let packet = `{"sender":"김코딩","receiver":"박해커","message":"해커야 오늘 저녁 같이 먹을래?","createdAt":"2021-01-12 10:10:10"}`
let obj = JSON.parse(packet)

console.log(obj)
/*
 * {
 * sender: "김코딩",
 * receiver: "박해커",
 * message: "해커야 오늘 저녁 같이 먹을래?",
 * createdAt: "2021-01-12 10:10:10"
 * }
 */

 console.log(typeof(obj))
 // `object`

JSON 사용 규칙

자바스크립트 객체JSON
키는 따옴표없이 쓸 수 있음
{key : "property' }
반드시 큰따옴표를 붙여야함
'{"key":"property"}'
문자열값작은 따옴표도 사용 가능
{ "key" : 'property' }
반드시 큰따옴표로 감싸야 함
'{"key":"property"}'
키와 값 사이 공백사용 가능
{"key" : 'property'}
사용 불가능
'{"key":"property"}'
키-값 쌍 사이 공백사용 가능
{ "key":'property', num:1 }
사용 불가능
'{"key":"property","num":1}'

📌 JSON.stringify 과제

JSON.stringify를 함수의 형태로 직접 구현하기

stringifyJSON.js

새로 알게된 내용

  • continue문은 지정된 루프의 현재 반복에서 명령문의 실행을 종료하고 반복문의 처음으로 돌아가여 다음 루프문 실행
  • forEach : 주어진 함수를 배열 요소를 각각 나열
    const array1 = ['a', 'b', 'c,];
    array1.forEach(element => console.log(element));	
    // Expected output: "a"
    // Expected output: "b"
    // Expected output: "c"
  • for..in문 : 객체에 있는 프로퍼티 키 열거 전용
    const obj = {
      name: 'curryyou',
      job: 'engineer'
    }
    for (const key in obj){
      console.log(`${key} : ${obj[key]}`);
    }
    // name : curryyou
    // job : engineer

[내가 쓴 코드]

function stringifyJSON(obj) {
  if(obj === null) {
    return 'null';
  }
  if( typeof obj === 'boolean' || typeof obj === 'number') {
    return `${obj}`;
  }
  if(typeof obj === 'string') {
    return `"${obj}"`;
  }
  // obj가 배열인 경우
  if(Array.isArray(obj)){
    let result = [];
    // forEach메서드 사용
    obj.forEach((el)=>{
      result.push(stringifyJSON(el));
    })
  	//
    return `[${result}]`;
  }
  // obj 객체인 경우
  if(typeof obj === 'object'){
    let result = "";
    // for..in문 사용)
    for(key in obj) {
  		// 객체안에 있는 키의 속성값이 빈배열이거나 함수일경우
      if(obj[key] === undefined || typeof obj[key] === "function"){
        // result = String(result)로 써도 됨;
        // 현재 반복에서 명령문 실행 종료하고 다음 명령문 실행
        continue;
  		// (,) 붙이고 마지막 배열에서는 빼줘야 함
      } else {
        result = result + `${stringifyJSON(key)}:${stringifyJSON(obj[key])},`;
      }
    }
    // 마지막의 ,을 없애주기 위해 result.length-1을 사용 
    result = result.slice(0, result.length-1);
    return `{${result}}`;
  }
};

// 다음 코드는 결과 제출을 위한 코드입니다. 신경 쓰지 않아도 좋습니다.
if (typeof window === "undefined") {
  module.exports = stringifyJSON;
}

[참고_pair가 쓴 코드]

function stringifyJSON(obj) {
  // your code goes here

  if (obj === null) {
    return "null";
  }

  if (typeof obj === "number" || typeof obj === "boolean") {
    return ${obj};
  }

  if (typeof obj === "string") {
    return "${obj}";
  }

  if (Array.isArray(obj)) {
    // 결과를 담을 빈배열 선언
    const result = [];
    // 배열을 순회하며 type체크
    for (let i = 0; i < obj.length; i++) {
      if (typeof obj[i] === "string") {
        // 문자열인 경우 문자열형태로 result에 담기
        result.push("${obj[i]}");
        // 배열안에 배열일 경우 (재귀)
      } else if (Array.isArray(obj[i])) {
        result.push(stringifyJSON(obj[i]));
      } else {
        // obj가 문자열이 아니고, 배열이 아닐경우 (재귀탈출조건)
        result.push(stringifyJSON(obj[i]));
      }
    }
    return [${result}];
  }
  // for문쓰기 싫을경우 배열메서드 map가능
  // 여기서는 따로 문자열 조건이 필요없는 이유가 stringifyJSON 함수 재귀를 돌며
  // string 조건에 자동으로 걸리기때문
  //   if (Array.isArray(obj)) {
  //   const elements = obj.map((element) => stringifyJSON(element));
  //   return [${elements}];
  // }

  if (typeof obj === "object") {
    const result = [];
    // 객체의 key순회
    for (let key in obj) {
      // 값부분에 객체 혹은 배열이 들어가기때문에, value에 재귀가 필요함
      const value = stringifyJSON(obj[key]);
      // key의 값이 있는경우 (undefined 예외조건 처리)
      if (value !== undefined) {
        result.push("${key}":${value});
      }
    }
    return {${result}};
  }
}


📌 Tree UI 과제

재귀를 사용해서 목록 구조 만들기

fix_me.js

새로 알게된 내용

  • element.setAttribute(속성명, 속성값)
  const input = document.createElement('input')
  input.setAttribute('type', 'checkbox') // = input.type = 'checkbox';
// index.html의 id가 root인 ul태그를 읽어옴
const root = document.getElementById('root');
// currentNode는 root를 동적인 요소(dom)으로 만든 내용?이 들어감
function createTreeView(menu, currentNode) {
  for(let i = 0; i < menu.length; i++) {
    // li 요소 생성 (li은 자식요소 유/무 둘다에도 있으니 먼저 생성)
    const li = document.createElement('li')
    // menu에 'children'없으면 check,span,ul없이 li만 있음 (Base)
    if(!menu[i].children) {
      li.textContent = menu[i].name; //li에는 메뉴 이름만 넣어주기
      currentNode.append(li); //currentNode에 li 넣어주기
    }
    // menu에 'children'있으면 checkbox,span,ul,li (recursive)
    else {
      const input = document.createElement('input')
      // input.type = 'checkbox';
      input.setAttribute('type', 'checkbox') // input태그에 'checkbox'속성주기
      const span = document.createElement('span')
      span.textContent = menu[i].name; // span태그에 메뉴 이름 넣기
      const ul = document.createElement('ul')
      // li 태그에 input, span, ul태그 넣기
      li.append(input, span, ul)
      currentNode.append(li);
      // 재귀함수 사용해서 자식요소에 자식요소가 있는지 확인해주기
      createTreeView(menu[i].children, ul);
    }
  }
}
// DOM 생성이 완료된 뒤에 함수 실행
createTreeView(menu, root);
                             

0개의 댓글