How can I get javascript to read from a .json file? How can I get javascript to read from a .json file? javascript javascript

How can I get javascript to read from a .json file?


Assuming you mean "file on a local filesystem" when you say .json file.

You'll need to save the json data formatted as jsonp, and use a file:// url to access it.

Your HTML will look like this:

<script src="file://c:\\data\\activity.jsonp"></script><script type="text/javascript">  function updateMe(){    var x = 0;    var activity=jsonstr;    foreach (i in activity) {        date = document.getElementById(i.date).innerHTML = activity.date;        event = document.getElementById(i.event).innerHTML = activity.event;    }  }</script>

And the file c:\data\activity.jsonp contains the following line:

jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];


NOTICE: AS OF JULY 12TH, 2018, THE OTHER ANSWERS ARE ALL OUTDATED. JSONP IS NOW CONSIDERED A TERRIBLE IDEA

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 = new XMLHttpRequest();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><p id="demo"></p><p>Take a look at <a href="json_demo.txt" target="_blank">json_demo.txt</a></p></body></html>