35

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?

MTP
  • 387
  • 1
  • 3
  • 8
  • 1
    Could you clarify if you mean "json file on a file system", or "json file hosted on a web server". – ironchefpython Jul 15 '11 at 17:58
  • Sorry....this is json file on a file system, stored in the same folder as the html page. – MTP Jul 15 '11 at 18:05
  • Then the answer I gave, using a jsonp formatted file, is what you're looking for. Don't forget to mark an answer accepted when your question has been answered satisfactorily. – ironchefpython Jul 15 '11 at 19:41
  • Does this answer your question? [How to read an external local JSON file in JavaScript?](https://stackoverflow.com/questions/19706046/how-to-read-an-external-local-json-file-in-javascript) – wesinat0r Dec 30 '19 at 21:35

5 Answers5

39

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"} ];
ironchefpython
  • 3,409
  • 1
  • 19
  • 32
  • THANK YOU...this was very helpful. However, I'm not sure yet how to access individual elements of the JSONP. I can print out all of 'activity' just fine, but if I try activity.date then it screams 'Undefined'. Any ideas as to why? I'm currently using alert() for testing. – MTP Jul 18 '11 at 14:51
  • Could you add an edit below your original question to show the contents of the JSONP file you're using? – ironchefpython Jul 18 '11 at 15:15
  • Your path for the .jsonp file will fail - the backslashes will be seen as escapes and I doubt the user has "c:dataactivity.jsonp" on their drive. file urls use forward slashes. – Marc B Jul 18 '11 at 15:17
  • Ah...you've still got to parse the jsonstr, so it'd look like: – MTP Jul 18 '11 at 15:22
  • 2
    var activity = JSON.parse(jsonstr) .... thereafter, you're good to go. Thank you so much for the help. – MTP Jul 18 '11 at 15:23
  • @ironchefpython can this be done leaving `activity.json` as is but assume it's a resource accessible from a web server? – greatwolf Jul 19 '13 at 05:42
  • Nice, thanks for the info... it worked... only thing is, the whole json has to be in a single line :) – ATOzTOA Jul 26 '13 at 05:33
  • Adding `jsonstr = ` to `activity.jsonp` means that it no longer is valid `JSON`. Although this answer shows how to load an external `.json` file it doesn't show how to read from an external `JSON` file. The change to `activity.json` now just makes this an example of how to create a variable in a separate javascript file and use it. – wuliwong Jun 19 '15 at 15:15
10

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/

Sheshank S.
  • 3,053
  • 3
  • 19
  • 39
  • @Shashank , Try it editor is really good. But I am not able to find the related documentation for the same. Can you please share the link to documentation related to W3Schools try it editor you shared? – Mohammed Atif Jul 13 '18 at 06:36
  • @MohammedAtif Sure! Remember if it helped to upvote :) https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax – Sheshank S. Jul 13 '18 at 14:53
5

Actually, you are looking for the AJAX CALL, in which you will replace the URL parameter value with the link of the JSON file to get the JSON values.

$.ajax({
    url: "File.json", //the path of the file is replaced by File.json
    dataType: "json",
    success: function (response) {
        console.log(response); //it will return the json array
    }
});
Junaid Shahid
  • 51
  • 1
  • 3
4

You can do it like... Just give the proper path of your json file...

<!doctype html>
<html>
    <head>
        <script type="text/javascript" src="abc.json"></script>
             <script type="text/javascript" >
                function load() {
                     var mydata = JSON.parse(data);
                     alert(mydata.length);

                     var div = document.getElementById('data');

                     for(var i = 0;i < mydata.length; i++)
                     {
                        div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
                     }
                 }
        </script>
    </head>
    <body onload="load()">
    <div id= "data">

    </div>
    </body>
</html>

Simply getting the data and appending it to a div... Initially printing the length in alert.

Here is my Json file: abc.json

data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';
Javed
  • 1,613
  • 17
  • 16
  • 3
    your file is not json. it is jsonp, which is why this works. for json, it does not. – eis Jun 24 '18 at 13:28
3

Instead of storing the data as pure JSON store it instead as a JavaScript Object Literal; E.g.

window.portalData = [
  {
    "kpi" : "NDAR",
    "data": [15,152,2,45,0,2,0,16,88,0,174,0,30,63,0,0,0,0,448,4,0,139,1,7,12,0,211,37,182,154]
  },
  {
     "kpi" : "NTI",
     "data" : [195,299,31,32,438,12,0,6,136,31,71,5,40,40,96,46,4,49,106,127,43,366,23,36,7,34,196,105,30,77]
  },
  {
     "kpi" : "BS",
     "data" : [745,2129,1775,1089,517,720,2269,334,1436,517,3219,1167,2286,266,1813,509,1409,988,1511,972,730,2039,1067,1102,1270,1629,845,1292,1107,1800]
  },
  {
     "kpi" : "SISS",
     "data" :  [75,547,260,430,397,91,0,0,217,105,563,136,352,286,244,166,287,319,877,230,100,437,108,326,145,749,0,92,191,469]
  },
  {
 "kpi" : "MID",
 "data" : [6,17,14,8,13,7,4,6,8,5,72,15,6,3,1,13,17,32,9,3,25,21,7,49,23,10,13,18,36,9,12]
  }
];

You can then do the following in your HTML

<script src="server_data.js"> </script>


function getServerData(kpiCode)
{
    var elem = $(window.portalData).filter(function(idx){
        return window.portalData[idx].kpi == kpiCode;
     });

    return elem[0].data;
};

var defData = getServerData('NDAR');
Vishnoo Rath
  • 550
  • 7
  • 22
  • Even better, start the file like `window.portalData = ` and place the `[ {` on the next line. Then you can process it as a real JSON file, by ignoring the first line. – gregn3 Oct 26 '19 at 15:38