Fetching data from a JSON file on my PC and using it in React

Viewed 33

I have an input field in my React app where I can select/drag'n'drop files from my PC. The file data looks like this:

{
  path: "/test/metadata.json",
  lastModified: 1657787087977,
  name: "metadata.json",
  size: 10,
  type: "application/json",
  webkitRelativePath: ""
}

Having selected a file, I'm trying to perform a fetch request if the file is of type JSON in order to extract the contents.

acceptedFiles.forEach(file => {
      if (file.path.includes('.json')) {
        fetch(file.path)
          .then(res => res.json())
          .then(data => console.log(data));
      }
    });

The output of the fetch request above is this:

Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

And the request URL looks like it's trying to fetch the file from localhost:3000 and fails.

http://localhost:3000/test/metadata.json

My question: Is it possible to select some JSON file for upload and performs a fetch request on it in order to get its' contents? Can this be done in a React app or will I need Node.js for this?

1 Answers

Seems like the JSON data is not valid. JSON data should be like this:

    {
      "path": "/test/metadata.json",
      "lastModified": 1657787087977,
      "name": "metadata.json",
      "size": 10,
      "type": "application/json",
      "webkitRelativePath": ""
    }
Related