ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Response.json()
    개발/Javascript 2022. 5. 6. 21:31

    Response 객체는 요청에 대한 응답을 나타내는 인터페이스입니다.

    fetch 함수를 통해서 데이터를 요청하면 resonse 객체로 받습니다.

    다음은 mdn의 예제 중 일부입니다.

        fetch('products.json')
        .then(function(response) {
          if (!response.ok) {
            throw new Error("HTTP error, status = " + response.status);
          }
          return response.json();
        })

    json()은 Response 인터페이스의 메소드이기 때문에 response는 Response 객체가 맞다는 것이 확인됩니다.

    json() 메소드는 json 객체를 반환할 것 같습니다. 메소드 이름이 json이니까요.

    다음은 mdn 문서에 나오는 설명입니다.

    The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON

    → json() 메소드는 리스폰스 인터페이스의 메소드입니다. 이 함수는 리스폰스 스트림을 가지며 완료될 때까지 읽습니다. body의 텍스트를 JSON으로 파싱한 결과로 해결되는 프로미스 객체를 반환합니다.

     

    조금 더 풀어서 말하면 JSON을 입력으로 받아 파싱하여 자바스크립트 객체로 만드는 것입니다.

    mdn에서 가져온 것으로 코드 전체는 다음과 같은데요.

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width">
    
        <title>Fetch json example</title>
    
        <link rel="stylesheet" href="style.css">
        <!--[if lt IE 9]>
          <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
      </head>
    
      <body>
        <h1>Fetch json example</h1>
        <ul>
        </ul>
    
      </body>
      <script>
        var myList = document.querySelector('ul');
    
        fetch('products.json')
        .then(function(response) {
          if (!response.ok) {
            throw new Error("HTTP error, status = " + response.status);
          }
          return response.json();
        })
        .then(function(json) {
          for(var i = 0; i < json.products.length; i++) {
            var listItem = document.createElement('li');
            listItem.innerHTML = '<strong>' + json.products[i].Name + '</strong>';
            listItem.innerHTML +=' can be found in ' + json.products[i].Location + '.';
            listItem.innerHTML +=' Cost: <strong>£' + json.products[i].Price + '</strong>';
            myList.appendChild(listItem);
          }
        })
        .catch(function(error) {
          var p = document.createElement('p');
          p.appendChild(
            document.createTextNode('Error: ' + error.message)
          );
          document.body.insertBefore(p, myList);
        });
    
      </script>
    </html>

    return response.json()이 아니라 return response를 하면 웹 페이지가 제대로 동작하지 않습니다.

    json() 메소드를 호출해야 완료될 때까지 데이터를 읽어 객체로 resolve 되는 프로미스 객체를 반환합니다.

    products.json은 key가 "products"이고 value가 객체를 요소로 가지는 배열입니다.

    { "products" : [
      { "Name": "Cheese", "Price" : 2.50, "Location": "Refrigerated foods"},
      { "Name": "Crisps", "Price" : 3, "Location": "the Snack isle"},
      { "Name": "Pizza", "Price" : 4, "Location": "Refrigerated foods"},
      { "Name": "Chocolate", "Price" : 1.50, "Location": "the Snack isle"},
      { "Name": "Self-raising flour", "Price" : 1.50, "Location": "Home baking"},
      { "Name": "Ground almonds", "Price" : 3, "Location": "Home baking"}
    ]}

     

     

     

     

     

     

     

    댓글

Designed by Tistory.