Importing JSON Files and Objects in Svelte

- 1 minute read

Consider the following data.json file:

    "fruit": "apple",
    "color: "red"

Here is an example Svelte component which imports data.json as an object called item:

    import item from 'path/to/data.json';

<!-- The "item" variable can be treated like a parsed object: -->

{item.fruit} <!-- prints "apple" -->

{item.color} <!-- prints "color" -->

Sometimes, you might want to just import the value of a root-level key from a JSON file, without importing the whole file.

To do this, you can place the top-level key in brackets in your import statement, like this:

    import { fruit } from 'path/to/data.json';

{fruit} <!-- prints "apple" -->

Keep in mind that the above examples have been tested in SvelteKit and might not work with out-of-the-box other Svelte environments or versions, depending on your bundler setup.

For example, if you’re using Svelte with Rollup, you might need to use a plugin like rollup-plugin-json.

Link to this section Conclusion

Anyway, this is the technique I use to pull JSON data from local files within my Svelte components, and I hope it helped you!