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"
}
]
}
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);
}
Top comments (7)
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):
For NodeJS:
agreed
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
orfs
and keep a consistent server applicationwell, 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 🤷🏻♂️
Ah thanks this is exactly what I needed.
In node:
err::
TypeError: Failed to parse URL from test.json
[cause]: TypeError [ERR_INVALID_URL]: Invalid URL
input: 'test.json',
code: 'ERR_INVALID_URL'
solution?
Read the other comment.