1

I have a JSON file stored in the same folder as an HTML file for a webpage I'm working on. This HTML file has a script with a function that takes data in a variable in JSON form. I'm having trouble getting the contents of the JSON file into a variable in my HTML file to be used by the function. I am running the HTML file locally.

I've tried the following:

$(function(){
    $.getJSON("./data.json", function(jsdata) {
        json = jsdata;
        console.log(json);
    });
});

However, it only results in: XMLHttpRequest cannot load file. Is there any way to parse a local JSON file in Javascript?

The JSON was validated using http://jsonlint.com/

Using "data.json" gives the same error as before.

Dagrooms
  • 1,507
  • 2
  • 16
  • 42

5 Answers5

3

Do not use a .. If the json file is in the same folder as the location your js is running (i.e. your html file), it should be this:

$(function(){
    $.getJSON("data.json", function(jsdata) {
        json = jsdata;
        console.log(json);
    });
});
Donal
  • 31,121
  • 10
  • 63
  • 72
  • XMLHttpRequest cannot load file:///C:/Users/grooms/Desktop/SampleTimeline/data.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. – Dagrooms Jun 04 '15 at 14:25
  • 2
    You need to run your html from a website - not from the from a directory on the file system. For more info, see here: http://stackoverflow.com/questions/371875/local-file-access-with-javascript – Donal Jun 04 '15 at 14:26
  • 2
    Good to know. I get the noob of the day award. – Dagrooms Jun 04 '15 at 14:29
2

You cannot load a local file using $.getJSON in jquery. You have to set a valid url of your file inside of your project, not a local file path because browser prevents it from loading for some security reason.

Akash Rajbanshi
  • 1,553
  • 11
  • 23
1

Dot in the url is causing the problem

Use this:

$.getJSON("/data.json", function(jsdata) { 
        json = jsdata;
        console.log(json);
    });
PHP Worm...
  • 4,109
  • 1
  • 25
  • 48
  • XMLHttpRequest cannot load file:///C:/data.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. – Dagrooms Jun 04 '15 at 14:25
1

The URL provided is wrong.

Use following:

$(function () {
    var baseUrl = 'http://....'; // Your base url of app

    // Use the absolute URL in here
    $.getJSON( baseUrl + "/data.json", function (jsdata) {
        json = jsdata;
        console.log(json);
    });
});
Tushar
  • 85,780
  • 21
  • 159
  • 179
0

try this code

$.ajax({
    url: "./data.json", // or "/data.json",
    type: "GET",
    dataType: "json"
})
Parag Bhayani
  • 3,280
  • 2
  • 28
  • 52