0

Trying to fetch json data from local file and keep getting

"JSON.parse: unexpected end of data at line 1 column 1" .

I have tried numerous parameters to the fetch function but I keep getting at least 1 error.

    function getData() {
      fetch('./data.json', {mode: 'no-cors'})
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
      })
    };

JSON Data

{
  "CustomerJohn": [
    {
      "month": "April",
      "transaction": 1,
      "price": 57
    },
    {
      "month": "April",
      "transaction": 2,
      "price": 89
    },
    {
      "month": "May",
      "transaction": 1,
      "price": 163
    },
    {
      "month": "May",
      "transaction": 2,
      "price": 43
    },
    {
      "month": "May",
      "transaction": 3,
      "price": 221
    },
    {
      "month": "June",
      "transaction": 1,
      "price": 99
    },
    {
      "month": "June",
      "transaction": 2,
      "price": 201
    }
  ]
}

I would like to console.log the data to make sure it if functioning properly.

Shankar
  • 2,890
  • 3
  • 25
  • 40
  • 3
    There might be an error while fetching your data. Could you check if the network tab of the chrome dev tool, what the call is returning. – Nicolas Nov 05 '19 at 19:08
  • The JSON you posted is valid, so there must be something different in the real application. – Barmar Nov 05 '19 at 19:09
  • 1
    What Nicolas said, I would assume that line 1 of the response is like a line break or something and the actual JSON data starts on line 2. – Ray Nov 05 '19 at 19:38
  • This is what Chrome is saying – Andrew Python Nov 05 '19 at 19:44
  • app.js:20 Fetch API cannot load file:///C:/data.json. URL scheme "file" is not supported. getData @ app.js:20 app.js:20 Uncaught (in promise) TypeError: Failed to fetch at HTMLButtonElement.getData (app.js:20) – Andrew Python Nov 05 '19 at 19:44

1 Answers1

2

You will always get error Fetch API cannot load file:///C:/your/path/to/data.json. URL scheme "file" is not supported. if you use fetch to retrieve the local file where you are not running the server i.e. accessing the JSON file by file:/// protocol and not by http:// or https://.

In order to access it, you must be in some server environment and can use XMLHttpRequest to retrieve the data. I've prepared working code for you below:

// Method which actually read json using XMLHttpRequest and promise
const jsonFileReader = async path => {
    return new Promise((resolve, reject) => {

        const request = new XMLHttpRequest();
        request.open('GET', path, true);
        request.responseType = 'blob';

        request.onload = () => {
          const reader = new FileReader();

          reader.onload = e => resolve(e.target.result);
          reader.onerror = err => reject(err);
          reader.readAsDataURL(request.response);
        };

        request.send();
    });
}

// This mthod will return the JSON
const returnJsonData = async (url) => {
    const jsonData = await jsonFileReader(url);
    console.log('Here is your JSON data: => ', jsonData);
    return jsonData;
}

// Calling the function where you put URL
returnJsonData('./file.json');

Also, if you not run this code on server, you will get following error, Access to XMLHttpRequest at 'file:///C:/your/path/to/data.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Reason is, again, the protocol and cross origin issue which is restricting you to access the file.

So even though your file originates from the same host (localhost), but as long as the scheme is different (http / file), they are treated as different origin.


How you can create quick server in Node.js

  1. Install http-server by typing npm install -g http-server
  2. Change into your working directory, where yoursome.html lives
  3. Start your http server by issuing http-server -c-1

This runs a Node.js httpd which serves the files in your directory as static files accessible from http://localhost:8080

Krishan Pal
  • 306
  • 1
  • 3