sig03
1 min readMay 18, 2020

--

javascript 에서 json 파일 include 하는 간단한 방법 두 가지

javascript 에서 json 파일을 include 하려는데 의외로 잘 안되서 반나절 정도 날려먹었다. 사용하려던 방법은 import 를 쓰거나 fetch로 가져오는 방법이다. http 로 가져오는 fetch 보다 import 가 간결하고 빠르리라 본다. 간단한건데 나름 애를먹은 것들이라 기록용으로 남겨본다.

1. import 사용

  • .json 으로 확장자를 만들면 브라우저가 아래와 같은 에러를 뿌린다.
  • Failed to load module script: The server responded with a non-JavaScript MIME type of “application/json”. Strict MIME type checking is enforced for module scripts per HTML spec.
  • .json 을 .js 로 만들고 안에다 export 로 감싸서 json 데이터를 넣어준다.
  • script 에 type=”module” 를 써줘야 인식한다.

//test.js

<script type=”module”>
import data from ‘./test.js’;
//const {word} = data;
console.log(data);
</script>

//data.js

export default
{
“fruit”: “Apple”,
“size”: “Large”,
“color”: “Red”
}

2. fetch 사용

  • 샘플 json 데이터를 {“fruit”: “Apple”,”size”: “Large”,”color”: “Red”} 이렇게 만들었더니 인식을 못한다. 아래와 같이 만들어야 함.

//test.js

<script>
fetch(‘http://www.domain.com/test.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
</script>

//test.json

{
“fruit”: “Apple”,
“size”: “Large”,
“color”: “Red”
}

--

--