Skip to content Skip to sidebar Skip to footer

Importing External "data.json" File Into Javascript Variable

This may be a duplicate, but I was unable to find a previously asked question that answers mine. I am wanting to import a .json file into my javascript like this: var array = 'data

Solution 1:

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

Solution 2:

If you have your JSON as a string, JSON.parse() will work fine. Since you are loading the json from a file, you will need to do a XMLHttpRequest to it. For example (This is w3schools.com example):

var xmlhttp = newXMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myObj.name;
    }
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
<!DOCTYPE html><html><body><h2>Use the XMLHttpRequest to get the content of a file.</h2><p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p><pid="demo"></p><p>Take a look at <ahref="json_demo.txt"target="_blank">json_demo.txt</a></p></body></html>

It will not work here as that file isn't located here. Go to this w3schools example though: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax

Here is the documentation for JSON.parse(): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Here's a summary:

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

Here's the example used:

var json = '{"result":true, "count":42}';
obj = JSON.parse(json);

console.log(obj.count);
// expected output: 42console.log(obj.result);
// expected output: true

If you don't want to use XMLHttpRequests, then a JQUERY way (which I'm not sure why it isn't working for you) is http://api.jquery.com/jQuery.getJSON/

Since it isn't working, I'd try using XMLHttpRequests

EDIT:

You could also try AJAX requests:

$.ajax({
    'async': false,
    'global': false,
    'url': "/jsonfile.json",
    'dataType': "json",
    'success': function (data) {
        // do stuff with data
    }
});

Documentation: http://api.jquery.com/jquery.ajax/

Post a Comment for "Importing External "data.json" File Into Javascript Variable"