Post

JSON 기본

JSON 기본

JSON 이란?

JSON

  • 데이터를 저장하고, 전송하기 위한 형식 중 하나.
  • 특징: 키-값 쌍으로 구성, 배열지원, 다양한 데이터 타입 가능, 주석 불가능, 마지막에 콤마(,) 불가
    • 가능한 데이터 타입: 문자열, 숫자, Boolean, 객체, 배열, null
  • 서버 통신에서 가장 많이 사용되는 데이터 형식

Fetch API

  • 네트워크 요청을 쉽게할 수 있도록 도와주는 Javascript의 인터페이스
  • 주로 json 데이터를 주고 받을 때 사용.
  • fetch Api로 서버에 요청 → json 형식으로 응답

Node.js

  • JavaScript서버에서도 실행할 수 있도록 함
  • JSONPlaceholder로 API 연동 테스트 진행.
    • JSONPlaceholder: API 연동을 테스트하거나 개발할 때,
      사용하는 무료 온라인 REST API 서비스
      JSONPlaceholder - Free Fake REST API
    • 실제 서버나 데이터베이스 없이도 JSON 형식의 데이터를 주고받는 연습을 할 수 있도록 도와주는 일종의 Mock API



실습

  1. 해당 사이트의 [My JSON Server] 클릭.
    Image

  2. [Beta]의 install JSON Server 클릭.
    Image

  3. 해당 github에 제시된 README 파일의 메뉴얼을 따른다.
    Image
    • Install
      Image
    • Usage db.json 파일을 생성하여, json 폴더 내에 위치시킨다.
      Image

      해당 db.json 파일을 JSON Server CLI에 넘겨준다.
      Image

  4. 동작을 위한 버튼이 담긴, fetch_get.html을 작성한다.
    • fetch_get.html (이벤트 작성전)
      • 코드
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        
          <!DOCTYPE html>
          <html lang="ko">
            <head>
              <meta charset="UTF-8" />
              <meta name="viewport" content="width=device-width, initial-scale=1.0" />
              <title>json 설명</title>
              <script>
                document.addEventListener("DOMContentLoaded", () => {
                  const getBtn = document.getElementById("getBtn");
                  const postBtn = document.getElementById("postBtn");
                  const putBtn = document.getElementById("putBtn");
                  const deleteBtn = document.getElementById("deleteBtn");
                    
                  getBtn.addEventListener("click", (e) => {
                  });
                });
              </script>
            </head>
            <body>
              <button type="button" id="getBtn">get</button>
              <button type="button" id="postBtn">post</button>
              <button type="button" id="putBtn">put</button>
              <button type="button" id="deleteBtn">delete</button>
            </body>
          </html>
        
  5. 테스트를 위한 코드를 이벤트 리스너에 작성 후, 실행한다.
    Image

This post is licensed under CC BY 4.0 by the author.