How to Read an External Local Json File in JavaScript

How to read an external local JSON file in JavaScript?

You cannot make a AJAX call to a local resource as the request is made using HTTP.

A workaround is to run a local webserver, serve up the file and make the AJAX call to localhost.

In terms of helping you write code to read JSON, you should read the documentation for jQuery.getJSON():

http://api.jquery.com/jQuery.getJSON/

Loading local JSON file

$.getJSON is asynchronous so you should do:

$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});

read local JSON file into variable

Here's a way to do it without jQuery.

First create this function:

function loadJSON(callback) {   
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', '../news_data.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(JSON.parse(xobj.responseText));
}
};
xobj.send(null);
}

Then you can use it by simply calling something like this:

loadJSON(function(json) {
console.log(json); // this will log out the json object
});

I found this by simply googling "read local json file javascript" (source)

Vanilla Javascript, how to read local JSON file

fetch() returns a Promise, so you don't need to create one yourself. Promise returned by fetch fulfills with a Response object on which you need to call .json() method to get the actual data. This method also returns a Promise, so you need to chain another then() method call.

fetch('./Data.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));

For details, see:

  • Using Fetch

Load local JSON file into variable

If you pasted your object into content.json directly, it is invalid JSON. JSON keys and values must be wrapped in double quotes (" not ') unless the value is numeric, boolean, null, or composite (array or object). JSON cannot contain functions or undefined values. Below is your object as valid JSON.

{
"id": "whatever",
"name": "start",
"children": [
{
"id": "0.9685",
"name": " contents:queue"
},
{
"id": "0.79281",
"name": " contents:mqq_error"
}
]
}

You also had an extra }.

read an external local JSON file into Javascript

For learning and testing locally, I highly recommend using Firefox. It's a great browser to develop with because it's pretty lax with respect to loading local files.

For example, it can load local files using xhr no problem.

Note that you can't load ANY file off the local system... just files "looking forward" from you HTML page (relative) "foo/bar/data.json", but not "C:/data.json".

Another thing to consider is that the local file system and http are two completely different animals. When a browser makes an "http request" it is assuming a header, response codes, and data will be coming back at it. Whereas when loading local files, there's no such thing as a header nor response codes because the "request" is just a system-level message to load raw data. One indicator of these differences is how when you drag and drop a file from your system into a browser window, you'll see file:/// vs a web page using http://

Hope this helps.

And one last thing. When you use the overrideMimeType("application/json"), you're asking the browser to parse the resulting response as json, not text. So you may want to try returning just the response?

function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
// callback(rawFile.responseText);
callback(rawFile.response);
}
};
rawFile.send(null);
}

That way you shouldn't have to parse the JSON later?

Alternatively, don't over-ride response, and handle JSON parsing like you're doing.

function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
//rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
};
rawFile.send(null);
}


Related Topics



Leave a reply



Submit