Artboard 16Google 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
919191NeiNon151516.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.

Before jumping all in with the import/assert combo; "Import assertions" have been reframed to "Import attributes".

import obj from "mod" with { "type": "json" }

Learn more about it in the new spec proposal.

Additional resources: 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 4 days ago.

Related Topics

Related Articles