Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 601
MTP Avatar asked Jul 15 '11 17:07

MTP


People also ask

How read data from JSON file and convert it to a JavaScript object?

Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON. parse('{"name":"John", "age":30, "city":"New York"}');

Which method convert JSON data to JavaScript?

JSON text/object can be converted into Javascript object using the function JSON. parse().


2 Answers

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"} ]; 
like image 85
ironchefpython Avatar answered Sep 19 '22 17:09

ironchefpython


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>

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: 42    console.log(obj.result);  // expected output: true

Here is a summary on XMLHttpRequests from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest:

Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in Ajax programming.

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

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/

like image 20
Sheshank S. Avatar answered Sep 16 '22 17:09

Sheshank S.