Software Develop/Web

[JavaScript] html 파일내에서 json 읽어 출력하기

jaywapp 2023. 1. 3. 20:41

개요

html 파일에서 local의 json 파일을 읽어 웹 페이지에 출력하고자 한다.

내용

Json 파일

[
    {
        "name" : "Messi",
        "birth" : "1987-06-24",
        "nation" : "Argentina"
    },
    {
        "name" : "Mbappé",
        "birth" : "1998-12-20",
        "nation" : "France"
    }
]

Html 파일

<meta charset="utf-8">
<head>
    <h1>Json Test</h1>
</head>

<body>
  <div class="grid" id="grid">
    <script type="text/javascript">

      let http = new XMLHttpRequest();

      function CreateElement(name, birth, nation){

        let li = document.createElement('li');
        let content = 'Name : ' + name + ' / birth : ' + birth + ' / nation : ' + nation;
        let text = document.createTextNode(content);

        li.append(text);

        return li;

      }

      http.onreadystatechange = function () {
        if (http.readyState == 4 && http.status == 200) {
          jsonfunc(this.responseText); //this = http
        }
      }

      // data.json 경로는 html 파일과 동일 폴더에 위치함.
      http.open("GET", 'data.json', true);
      http.send();

      function jsonfunc(jsonText) {

        // String -> json으로 변환
        let json = JSON.parse(jsonText); 

        // ul Element 생성
        var ul = document.createElement('ul');

        for(var i = 0; i < json.length; i++){
            const player = json[i];

            // li Element 생성
            let li = CreateElement(
                player.name, 
                player.birth, 
                player.nation);

            ul.append(li);
        }

        document.getElementById("grid").append(ul);
      }
    </script>
  </div>
</body>

결과

https://github.com/jaywapp/Tutorials.Web/tree/master/Node.js/230103_2