Artboard 16light, inspiration, solution, idea, innovation,ionicons-v5_logosGoogle Sheets iconSwift icon
Published at
Updated at
Reading time
2min

If you're using EcmaScript modules, you probably know the problem that you can't "just" import JSON files. To import and load a JSON file in an ES module, you have to do a "window.fetch dance" to request the file and parse it yourself. It's not great...

But there's hope! According to chromestatus.com, JSON Modules are shipping in Chrome 91. I gave it a quick try, and surprisingly, the following JavaScript code does not work.

<script type="module">
  import data from "./data.json";
  console.log(data);
</script>

It throws the following exception in Chrome 91:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/json". Strict MIME type checking is enforced for module scripts per HTML spec.

I didn't have a detailed look at the spec discussion about this topic, but apparently, the new syntax to import JSON Modules is the following. 😲

import data from "./data.json" assert { type: "json" };

console.log(data);

That's quite something, and I have to do some reading about it. But hey, anything that makes it easier to import JSON is more than welcome!

What's the browser support?

MDN Compat Data (source)
Browser support info for Import assertions
chromechrome_androidedgefirefoxfirefox_androidsafarisafari_iossamsunginternet_androidwebview_android
919191NeiNΓΆ151516.091

At the time of writing, we're still waiting for Firefox to join the party.

If you're wondering about Node.js, importing JSON files are marked as experimental in the current LTS.

Edit: Axel Rauschmayer shared that JSON imports are based on import assertions and you can read more about it on his blog.

Was this snippet helpful?
Yes? Cool! You might want to check out Web Weekly for more snippets. The last edition went out 3 days ago.

Related Topics

Related Articles