Load Local JSON File into Variable

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

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/

Importing external data.json file into javascript variable

This is how you import json file to javascript. Once the json file is imported, you can use arr variable which stores json value.

var arr = null;
$.ajax({
'async': false,
'global': false,
'url': "/data.json",
'dataType': "json",
'success': function (data) {
arr = data;
}
});

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

load json into variable

This will do it:

var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': my_url,
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();

The main issue being that $.getJSON will run asynchronously, thus your Javascript will progress past the expression which invokes it even before its success callback fires, so there are no guarantees that your variable will capture any data.

Note in particular the 'async': false option in the above ajax call. The manual says:

By default, all requests are sent
asynchronous (i.e. this is set to true
by default). If you need synchronous
requests, set this option to false.
Note that synchronous requests may
temporarily lock the browser,
disabling any actions while the
request is active.



Related Topics



Leave a reply



Submit