본문 바로가기
소프트웨어/자바스크립트

[자바스크립트] 브라우저에서 JSON 파일 불러오기

by 만들오 2022. 8. 4.
728x90
브라우저에서 로컬에 저장된 .json 파일을 불러와 파싱하는 코드입니다.

실행 이미지

 

load_local_file.html
0.00MB
test.json
0.00MB


load_local_file.html
<!DOCTYPE html>
<html>

<head>
    <title>Load local .json file</title>
</head>

<body>
    <button onclick="loadFile()">Load</button>
</body>
<script defer>
    let data;
    const loadFile = () => {
        const input = document.createElement("input");
        input.type = "file";
        input.onchange = evt => {
            const selectedFile = evt.target.files[0];
            processJSON(selectedFile);
        };
        input.click();
    }

    const processJSON = file => {
        const reader = new FileReader();
        reader.onload = () => {
            data = JSON.parse(reader.result);
            console.log(data);
        }
        reader.readAsText(file);
    }


</script>

</html>

test.json
{
  "author" : "Mandloh",
  "blog" : "https://mandloh.tistory.com/",
  "age" : 100
}

[끝].

댓글