DEV Community

Discussion on: How To Read a local JSON File Using Fetch API

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

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
 
thomasheideman profile image
ThomasHeideman

well, actually I needed just this earlier this week, when i was experimenting with some practice project and i noticed i was running out of free api calls, so i created a mock JSON file and fetched that instead 🤷🏻‍♂️

Collapse
 
oztk profile image
Paul Duguet

It's very convenient when you need to mock some external service in a test environment. It means you can read a local file without having to conditionally use require or fs and keep a consistent server application

Collapse
 
tobyschonrock profile image
toby-schonrock

Ah thanks this is exactly what I needed.

Collapse
 
roshan_100kar profile image
Roshan Shambharkar

agreed