Skip to content

Instantly share code, notes, and snippets.

@zettacristiano
Created October 16, 2017 11:14
Show Gist options
  • Save zettacristiano/5ac78413001e482b12a86799be74f62f to your computer and use it in GitHub Desktop.
Save zettacristiano/5ac78413001e482b12a86799be74f62f to your computer and use it in GitHub Desktop.
Access local JSON data with Javascript
[{
"name": "Harry",
"age": "32"
}]

What

An updated guide/collection of guides on how to access JSON data with JavaScript

Original Question on Stack Exchange.


Example 1

For reading the external Local JSON file (data.json) using java script

data = '[{"name" : "Ashwin", "age" : "20"},{"name" : "Abhinandan", "age" : "20"}]';

// Mention the path of the json file in the script source along with the javascript file.

<script type="text/javascript" src="data.json></script>
<script type="text/javascript" src="javascrip.js"></script>

2.Get the Object from the json file

var mydata = JSON.parse(data);
 alert(mydata[0].name);
 alert(mydata[0].age);
 alert(mydata[1].name);
 alert(mydata[1].age);

http://www.askyb.com/javascript/load-json-file-locally-by-js-without-jquery/


Example 2

Depending on your browser, you may access to your local files. But this may not work for all the users of your app.

To do this, you can try the instructions from here: http://www.html5rocks.com/en/tutorials/file/dndfiles/

Once your file is loaded, you can retrieve the data using:

var jsonData = JSON.parse(theTextContentOfMyFile);
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'file.json', true);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
// .open will NOT return a value but simply returns undefined in async mode so use a callback
callback(xobj.responseText);
}
}
xobj.send(null);
}
// Call to function with anonymous callback
loadJSON(function(response) {
// Do Something with the response e.g.
//jsonresponse = JSON.parse(response);
// Assuming json data is wrapped in square brackets as Drew suggests
//console.log(jsonresponse[0].name);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment