简体   繁体   中英

Parse JSON File in Javascript

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.

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

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

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.

Dot in the url is causing the problem

Use this:

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

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);
    });
});

try this code

$.ajax({
    url: "./data.json", // or "/data.json",
    type: "GET",
    dataType: "json"
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM