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

MTP picture MTP · Jul 15, 2011 · Viewed 98.9k times · Source

My script currently looks like this:

<script type="text/javascript">
  function updateMe(){
    var x = 0;
    var jsonstr = '{"date":"July 4th", "event":"Independence Day"}';
    var activity=JSON.parse(jsonstr);
    while(x<10){
    date = document.getElementById("date"+x).innerHTML = activity.date;
    event = document.getElementById("event"+x).innerHTML = activity.event;
    x++;
    }
  }
</script>

Where date"x" and event"x" are a series of html tags. This function runs when the page loads (onload). My goal is to do this exact same thing, only from a local .json file as opposed to the hard code that I've got above. I've already checked out http://api.jquery.com/jQuery.getJSON/.

The local .json file looks like this:

{"date":"July 4th", "event":"Independence Day"}

Any suggestions?

Answer

ironchefpython picture ironchefpython · Jul 15, 2011

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"} ];