I'm currently trying to read a JSON I have in my project and render a table with its information using React. I was wondering how people do this common task, because I always tend to get stuck when this part comes on. My personal preference is to use the fetch API, and everytime I use external APIs it works like a charm. However, when reading local files like this:
fetch('../data.json')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
}).catch(function (error) {
console.log(error);
});
it raises errors all the time, telling me the classic:
SyntaxError: Unexpected token < in JSON at position 0
I'm starting to think that React doesn't find the file, but data.json is one folder level up from the js file where I use fetch, and the path I specify is correct (using ../).
Nevertheless, I'd like to find out how you usually prefer to do this. Hopefully it is an easier an more effective way than mine. Every alternative you recommend is highly appreciated!
Read this blog on how to read the JSON file in a local file? are you some face issue plz read a post on the medium may be your help click here
Rajdeep Singh
Build, Test and Deploy
If you are using some way to read data from a local file. Then just read it using this method.
1) I would expect you to be using some build system like webpack or browserify or something of that sort. You can probably tweak that a bit to accept reading of json files as well and just get that file using the ES5 stlye require or ES6 way using import .
2) Else, if you want to read it over streams or something like that try using the fs from node.
Cheers Hope this helps :)
John Eisenberg
fetchexpects a URL.../data.jsonis not a valid resource URL and hence it is not able to load it. Somehow you have to makedata.jsonavailable over HTTP (either by putting it in your public directory or by creating a route). Only thenfetchcan load it.