Sign in
Log inSign up

How do you usually prefer to read a local JSON file?

Alex's photo
Alex
·Mar 20, 2018

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!