DEV Community 👩‍💻👨‍💻

Roshan Shambharkar
Roshan Shambharkar

Posted on • Updated on

How To Read a local JSON File Using Fetch API

How To Read a local JSON File Using Fetch API

Can I use Fetch on a local JSON file?

  • The standard method that can be used to read

  • JSON files (either locally or uploaded to a server) is the Fetch API.

  • Use the same syntax for both. The only difference is the URL

First Create A .JSON file With name test.json

{
"countries":[
{
   "name": "Indonesia",
   "capital": "Jakarata"
},
{
   "name": "Philippines",
   "capital": "Manila"
  }
 ]
}
Enter fullscreen mode Exit fullscreen mode

Then create JavaScript file give name fetch.js

fetch("test.json")
.then(response => response.json())
.then(data => showInfo(data));

function showInfo(data) {
console.table(data.countries);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas • Edited on

Although I admit I didn't ever think this would work, I should ask why is even needed. If you are in a browser, you cannot fetch from the user's file system, and definitely cannot from the server's file system. On the other hand, if you are doing NodeJS, you have the fs module to actually read the file system.

And in both cases, you can statically import JSON.

For the browser (in React, for example):

import myJson from "./myJson.json";
Enter fullscreen mode Exit fullscreen mode

For NodeJS:

import myJson from "./myJson.json" assert { type: 'json' };
Enter fullscreen mode Exit fullscreen mode
Collapse
 
roshan_100kar profile image
Roshan Shambharkar Author

agreed

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.