Opens an external site in a new window
Mental Health Awareness Month
“Community”
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Links
  • Profile
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Links

SvelteKit JSON Import: use JSON Data in Svelte # SvelteKit JSON Import: use JSON Data in Svelte #

blurry low resolution placeholder image SvelteKit Secure Dev Server
  1. Home Rodney Lab Home
  2. Blog Posts Rodney Lab Blog Posts
  3. SvelteKit SvelteKit Blog Posts
<PREVIOUS POST
NEXT POST >
LATEST POST >>

SvelteKit JSON Import: use JSON Data in Svelte #

Published: 3 years ago
5 minute read
Gunning Fog Index: 5.7
3 comments
Content by Rodney
blurry low resolution placeholder image Author Image: Rodney from Rodney Lab
SHARE:

🖥 SvelteKit JSON Import #

There are many applications for SvelteKit JSON import. You might be building a client site, for example, and want to let the client update data for certain pages from time-to-time. It could also be a business app you are building which you want to read JSON data updated as part of a regular business process. Leaving aside not being able to add comments, JSON is a great format for storing data and is easily human-readable. On top, it can be updated without any JavaScript knowledge and little technical experience.

In this short video, we see how you can import entire JSON files into your Svelte components. On top, Vite makes it possible to extract certain objects or arrays from JSON and import just what you need, keeping your pages lean. If you're ready to see all that, hit play and sit back!

📹 SvelteKit JSON Import: Video #

Please enable JavaScript to watch the video 📼

SvelteKit JSON Import

🗳 Poll #

What’s your “go to” data format?
Voting reveals latest results.

🖥 SvelteKit JSON Import: Code #

+page.svelte
svelte
    
1 <script>
2 // import entire JSON file as a default import
3 import people from '$lib/data/people.json';
4
5 // import root level object as a named import
6 import { sponsors } from '$lib/data/clientsSponsors.json';
7
8 import '@fontsource/open-sans/400.css';
9 import '@fontsource/open-sans/700.css';
10
11 const BULLET_ENTITY = '•';
12 const EM_SPACE_ENTITY = ' ';
13
14 // we access the root level sponsors element (which is an array) directly in code
15 const sponsorString = sponsors
16 .map((element) => element.name)
17 .join(`${EM_SPACE_ENTITY}${BULLET_ENTITY}${EM_SPACE_ENTITY}`);
18 </script>
19
20 <svelte:head>
21 <title>About Us</title>
22 </svelte:head>
23
24 <header class="heading">
25 <div class="title">
26 <h1>About Us</h1>
27 </div>
28 </header>
29 <main>
30 <section class="sponsors">
31 <h2>Our Sponsors</h2>
32 <div class="scrolling-text"><p>{sponsorString}</p></div>
33 </section>
34 <section>
35 <h2>Our People</h2>
36 <div class="people">
37 <!-- We can access the people default import which is an array directly in the code -->
38 {#each people as { firstName, lastName, jobTitle, email }, index}
39 <article aria-posinset={index + 1} aria-setsize={people.length} class="person">
40 <h2>{firstName} {lastName}</h2>
41 <p><strong>{jobTitle}</strong></p>
42 <p>{email}</p>
43 </article>
44 {/each}
45 </div>
46 </section>
47 </main>

Bonus: Typed JSON imports #

You can get types from imported JSON by updating the jsconfig.json or tsconfig.json file in the project root folder. Just add the two highlighted lines:

jsonconfig.json
json
    
1 {
2 "compilerOptions": {
3 "baseUrl": ".",
4 "paths": {
5 "$lib": ["src/lib"],
6 "$lib/*": ["src/lib/*"]
7 },
8 "resolveJsonModule": true,
9 "esModueInterop": true
10 },
11 "extends": "./.svelte-kit/tsconfig.json",
12 "include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"]
13 }

🔗 SvelteKit JSON Import: Links #

  • Starting out Svelte and SvelteKit tutorial ,
  • Video on Svelte each blocks,
  • Full code for the demo site ,
  • Vite docs on JSON ,
  • Mockaroo test data generation ,
  • Svelte docs on each blocks 

🏁 Readable and Writable Svelte Stores: Summary #

Can you import local JSON files into Svelte components? #

Yes. SvelteKit uses Vite tooling which lets you import JSON files in addition to, for example, all file in a folder matching a pattern (glob imports). Unlike glob imports, there are no promises involved, and you can import an entire JSON file as a default import using the regular syntax: import data from '../data.json'. If you only need part of the file, you can also use a named import to import root level elements from the JSON file.

How do you import part of a JSON file in Vite? #

You can import the entire JSON file as the default export. Alternatively, you can import any root level element as a named import. For example, if the JSON file structure is { sponsors: ['sponsor1', 'sponsor2'], clients: ['client1', 'client2']}, both sponsors and clients are root level arrays. You can import either of these as a named import into a Svelte component file, for example, using SvelteKit. That is because SvelteKit uses Vite tooling. The import syntax is just what you will already be familiar with, e.g. import { clients, sponsors } from '../data.json';. Importing named imports in this way can be more efficient as it helps with tress shaking. Tree shaking is just the process of eliminating unused or dead code, to keep apps as lean as they can be.

How do you get types on imported JSON in SvelteKit? #

SvelteKit supports JSON imports out-of-the-box. To get types on the imported JSON though, you just need to add a couple of lines of code to `jsconfig.json` or `tsconfig.json` (whichever you have in your project). With those changes, you will get in-editor type checking and be able to display the type of an imported JSON variable by hovering over it. To get this working, just add these two lines under compiler options: `"resolveJsonModule": true,` and `"esModueInterop": true`.

What are the advantages of using JSON input data with SvelteKit? #

JSON is easy to read and understand, even by people with little technical expertise. It is also a popular data output format for business apps. Accepting JSON input data can make your app more useful to an end client, allowing them to update inputs themselves, without coding knowledge. There may be small data inputs which live outside a more formal CMS. When these inputs need updating from time-to-time JSON is a nice choice. An example might be the office locations for a small business on their brochure site.

🙏🏽 Feedback #

If you have found this video useful, see links below for further related content on this site. I do hope you learned one new thing from the video. Let me know if there are any ways I can improve on it. I hope you will use the code or starter in your own projects. Be sure to share your work on Twitter, giving me a mention, so I can see what you did. Finally, be sure to let me know ideas for other short videos you would like to see. Read on to find ways to get in touch, further below. If you have found this post useful, even though you can only afford even a tiny contribution, please consider supporting me through Buy me a Coffee.

blurry low resolution placeholder image ask Rodney X (formerly Twitter) avatar

Rodney

@askRodney

Just updated the video where we take a look at Vite JSON imports in more detail.

We now use the new SvelteKit routing API.

Hope you find it useful!

#askRodneyhttps://t.co/zDf0vmdrfA

— Rodney (@askRodney) October 17, 2022

Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter and also askRodney on Telegram . Also, see further ways to get in touch with Rodney Lab. I post regularly on SvelteKit as well as Search Engine Optimization among other topics. Also, subscribe to the newsletter to keep up-to-date with our latest projects.

Thanks for reading this post. I hope you found it valuable. Please get in touch with your feedback and suggestions for posts you would like to see. Read more about me …

blurry low resolution placeholder image Rodney from Rodney Lab
TAGS:
SVELTEKIT

Reposts:

Reposts

  • DaHackaz profile avatar

Likes:

Likes

  • Martin Nitsche profile avatar
  • Richard Mace profile avatar
Reposts & likes provided by Mastodon & X via Webmentions.

Related Posts

blurry low resolution placeholder image Parsing JSON Game Data: Read JSON in C++ GameDev 🕹️

Parsing JSON Game Data: Read JSON in C++ GameDev 🕹️

c++
gaming
<PREVIOUS POST
NEXT POST >
LATEST POST >>

Leave a comment …

Your information will be handled in line with our Privacy Policy .

Comments

  • Dave

    Hi Rodney, I'm good with the static importing of files as shown above. But I have a somewhat related problem... In sveltekit, I have a number of routes, each directory with a +page.svelte file and an associated problems.js file. problem.js contains a title and subtitle (and much more but not relevant at this point). My page.svelte imports its adjacent problem.js and passes the data (title, etc) to a Header.svelte component. Every page.svelte file has this identical functionality. I would like to put this common functionality in +layout.svelte and presume I have to load each problem.js file from a common layout.js file. I have tried various combinations of load, fetch, etc but without any luck. Any thoughts on how to do this? If you have the time to answer this, thanks very much. It might even be of interest to others so could be a little lesson of yours? ;) Any, Happy New Year from an ex-Brit in Canada. Cheers, Dave

    3 years ago
    • Rodney

      Hi Dave, Happy New Year and thanks for the feedback! Yep, I am not sure it would be possible to have the dynamic imports in a layout file. Would it be a pain to move all the problems data to a single file? You could have an object in there with a key for each route and the value as whatever data you need. In the layout file you can just extract the element for the current route. Does that make sense? Alternative is to keep existing indiv. files and export data from each, then import those as elements into the single file mentioned previously. Then use single file as before.
      3 years ago
    • Sam

      Hey Rodney, thanks for the fantastic blog post. I'm curious, what would the nested JSON object look like with the key, value pairs for the url route and data relationship. I'm just a little confused on what that might look like.
      10 months ago

Ask for more

1 Nov 2022 — Astro Server-Side Rendering: Edge Search Site
3 Oct 2022 — Svelte eCommerce Site: SvelteKit Snipcart Storefront
1 Sept 2022 — Get Started with SvelteKit Headless WordPress

Copyright © 2020 – 2025 Rodney Johnson. All Rights Reserved. Please read important copyright and intellectual property information.

  • Home
  • Profile
  • Plus +
  • Newsletter
  • Contact
  • Links
  • Terms of Use
  • Privacy Policy
We use cookies  to enhance visitors’ experience. Please click the “Options” button to make your choice.  Learn more here.