본문 바로가기
개발/JavaScript

2023.04.13 JavaScript의 에이싱크, JSON

by 상달군 2023. 4. 14.
728x90

1. JavaScript의 에이싱크(Async / Await)

  • Async / Await
  • Async 실습

2. JavaScript의  JSON(JavaScript Object Notation)

  • JSON의 특징
  • JSON의 구조
  • JSON의 메소드
  • JSON 보는팁들 
    • 크롬환경
    • 검증사이트

1. Async / Await (에이싱크) 비동기

  • 프로미스 문법을 조금더 쉽게 사용할수 있게 해주는 ES7에 추가된 문법
  • callback, Promise 비동기처리를 좀 더 쉽게 처리할 수 있도록 사용 됨
  • ES7에 추가된 문법

✔async를 사용하면서 유의할점 3가지 !!!


    1. promise(비동기 처리될 함수)를 만들고자 하는 함수 앞에 async를 붙여준다. 
    2. promise 앞에 await를 붙여줍니다. 
    3. retrun되는값이 무조건 프로미스의 resolve()값과 동일 
     - 1,2,3은 무조건 지켜줘야한다.

        async function  함수명(){
            ...
            // promise 앞에 await를 붙여줍니다. 

            return 값; // retrun되는값이 무조건 프로미스의 resolve()값과 동일 
        }

 


1-1.문제 6.async실습.)

 - 프로미스 2 코드를 async / await를 이용하여 만들기 

 

    <script>
        function fetchEgg(chicken) {
            return Promise.resolve(`${chicken} => 🥚`);
        }

        function fryEgg(egg){
            return Promise.resolve(`${egg} => 🍳`);
        }

        function getChicken(){
            return Promise.resolve(`🐤 => 🐓`);
        }

        async function makeFriedEgg(){
            let chicken;
            try{
                chicken = await getChicken();

            }catch{
                chicken = '🐥';
            }
            const egg = await fetchEgg(chicken);
            return fryEgg(egg);
        }

        makeFriedEgg()
            .then(console.log);

    </script>

🔴이부분의 코드를 잘 이해야합니다. 

        async function makeFriedEgg(){
            let chicken;
            try{
                chicken = await getChicken();

            }catch{
                chicken = '🐥';
            }
            const egg = await fetchEgg(chicken);
            return fryEgg(egg);
        }

2. JavaScript의  JSON(JavaScript Object Notation)

  • 데이터를 저장하거나 전송할 때 사용되는 경량의 Data 교환 방식
  • 사람과 기계 모두 이해하기 쉬우며 용량이 작아서 XML을 대체하여 데이터전송등에 많이 사용된다.
  • 데이터 포멧일 뿐, 통신 방법도 프로그래밍 문법도 아님
  • XML은 요즘 잘안쓰고 경량급인 JSON을 쓰기 시작했다.
     --우리는 JSON형태를 공부할것이다.

2-1.JSON의 특징

  • 서버와 클라이언트간의 교류에서 일반적으로 많이 사용된다.
  • 자바스크립트를 이용하여 JSON 형식의 문서를 자바스크립트 객체로 변환하기가 쉽다.
  • 자바스크립트 문법과 굉장히 유사하지만 텍스트 형식일 뿐이다.
  • 특정 언어에 종속되지 않으며, 대부분 프로그래밍 언어에서 JSON 포멧의 데이터를 핸들링 할 수 있는 라이브러리를 제공 하고있다.

 

                              {"name":"루시", "age":14, "family":"포메", "weight":3.5 }

✔ JSON은 이름과 값으로 구성된 프로퍼티의 정렬되지 않은 집합이며, 메소드 프로퍼티가 없다.


2-2. JSON의 구조

  • 이름과 값의 쌍으로 이루어짐
  • 데이터는 쉼표로 구분하여 나열
  • {}중괄호로 감싸 표현한다.
  • 배열은 []대괄호로 감싸 표현한다. 

2-3. JSON의 타입

  • 숫자, 문자열, 불리언, 객체, 배열, null

   표현해보기
    {
        "class":
        [// 하나의 배열안에 여러개의 객체가 존재 할수 있다.
            {"name":"김사과", "age":20, "hp":"010-1111-1111","pass":true},
            {"name":"반하나", "age":30, "hp":"010-1111-2222", "pass":false},
            {"name":"오란지", "age":25, "hp":"010-1111-3333", "pass":true}
        ],
        [
            .....
        ]
    }

2-4. 메소드들 (JSON객체 안에 들어있다.)

 stringify(Object)
  - 객체를 문자열로 변환해준다.
 parse(JSON)
  - 문자열 데이터를 자바스크립트 객체로 변환해준다.
 fetch api
  - Request나 Response와 같은 객체를 이용하여 HTTP 프로토콜을 통해 원격지의 정보를 가져오기 위해 사용하는 api이다. 
  - Promise를 기반으로 동작한다. 
    발전 흐름
    Ajax -> XMLHttpRequest() -> fetch API

 

실습 stringify(Object), parse(JSON) 예제)

    <script>
        const dog = {
            name : '루시',
            age : 14,
            family : '포메',
            eat: () =>{
                console.log('잘먹고 잘논다.');
            }
        };

        const json = JSON.stringify(dog); // JSON을 문자열 형태로 바꿈
        console.log(dog);
        console.log(json); //문자열로 바뀐 json을 출력

        const obj = JSON.parse(json); // 문자열을 다시 객체 형태로 바꿈
        console.log(obj);
    </script>

fetch api 예제)

 - JSON 공개 자료 (공부용)

 - https://www.7timer.info/bin/astro.php?lon=113.2&lat=23.1&ac=0&unit=metric&output=json&tzshift=0 

 

https://www.7timer.info/bin/astro.php?ac=0&lat=23.1&lon=113.2&output=json&tzshift=0&unit=metric

 

www.7timer.info

<head>
	<script>
        function fetchAPI(){
            return fetch('https://www.7timer.info/bin/astro.php?lon=113.2&lat=23.1&ac=0&unit=metric&output=json&tzshift=0')
                .then((response) => response.json())
                .then((data) => data);
        }

        fetchAPI().then((datas)=> {
            console.log(datas.dataseries); // datas에서 Array 만 뽑아냄
            showDatas(datas.dataseries); // 24개의 Array
        });

        function showDatas(datas){
            const ul = document.querySelector('#dataseries');//아래 ul id가 dataseries인 놈을 불러옴
            ul.innerHTML = datas.map((data)=> setLiElement(data)).join('');
        }

        function setLiElement(data){
            return `<li>cloudcover:${data.cloudcover}, lifted_index:${data.lifted_index}, prec_type:${data.prec_type}, rh2m:${data.rh2m}, seeing:${data.seeing}, temp2m:${data.temp2m}, timepoint:${data.timepoint}, transparency:${data.transparency}</li>`;
        }

    </script>
</head>
<body>
    <h2>fetch</h2>
    <ul id="dataseries">

    </ul>
</body>



✔ 크롬에서 JSON 쉽게 보는법 

 - 크롬 설정 -> 확장프로그램 -> chrome 웹 스토어 열기 ->JSON Formatter확장 시키기 

✔ JSON 검증 사이트

https://jsonlint.com/

 

The JSON Validator

JSONLint is the free online validator and json formatter tool for JSON, a lightweight data-interchange format. You can format json, validate json, with a quick and easy copy+paste.

jsonlint.com

 

728x90

댓글