0

So I've looked and looked and looked at different answers on StackExchange and other web forums and I still don't understand this. I've got a .json file that contains the information from an excel document. I want to display it on a web browser -> the easiest way to do this seems to be writing it in html.

How do I open the JSON file with html?? I'm happy with having the entire JSON file displayed on the html script but I would love to be able to set is as a variable and pull things out of it like a normal JSON object.

I have the code below for making a table which is what I want to do - but the real JSON object is in a separate file.

<html>
<head>
<title>Creation of array object in javascript using JSON</title>
<script language="javascript" >

document.writeln("<h2>JSON array object</h2>");

var books = { "Pascal" : [ 
      { "Name"  : "Pascal Made Simple", "price" : 700 },
      { "Name"  : "Guide to Pascal", "price" : 400 }
   ],                       
   "Scala"  : [
      { "Name"  : "Scala for the Impatient", "price" : 1000 }, 
      { "Name"  : "Scala in Depth", "price" : 1300 }
   ]    
}    

var i = 0
document.writeln("<table border='2'><tr>");
for(i=0;i<books.Pascal.length;i++)
{   
   document.writeln("<td>");
   document.writeln("<table border='1' width=100 >");
   document.writeln("<tr><td><b>Name</b></td><td width=50>"
   + books.Pascal[i].Name+"</td></tr>");
   document.writeln("<tr><td><b>Price</b></td><td width=50>"
   + books.Pascal[i].price +"</td></tr>");
   document.writeln("</table>");
   document.writeln("</td>");
}

for(i=0;i<books.Scala.length;i++)
{
   document.writeln("<td>");
   document.writeln("<table border='1' width=100 >");
   document.writeln("<tr><td><b>Name</b></td><td width=50>"
   + books.Scala[i].Name+"</td></tr>");
   document.writeln("<tr><td><b>Price</b></td><td width=50>"
   + books.Scala[i].price+"</td></tr>");
   document.writeln("</table>");
   document.writeln("</td>");
}
document.writeln("</tr></table>");
</script>
</head>
<body>
</body>
</html>

To clarify: The above code works great; but I want to do it with the contents of a .json file saved on my local drive.

Thanks in advance.

Isa
  • 149
  • 6
  • 15
  • To load in JSON outside of the initial HTML page, you'll need to do so using a background request (commonly called AJAX). The easiest way for you to load JSON data would be to make use of a Javascript library with solid documentation, examples, etc as well as an easy interface for doing what you want. [Jquery can help you there](http://api.jquery.com/jQuery.getJSON/) – Brian Jun 24 '14 at 23:51
  • Thank you to everyone who replied! I'm going to try out all of these answers and see which works best for my project. Follow-up question: A lot of people mentioned jquery (@Brian) is this widely considered the "correct" way of doing this? Should I just go ahead and download it? – Isa Jun 25 '14 at 16:15
  • jQuery isn't the "correct" way of doing it, but making your own AJAX calls is a very complicated process as opposed to calling jQuery's `getJSON` method. Your code suggests to me that you're relatively new to Javascript development (nothing wrong with that we all were once :P) and as such, a library like jQuery may be a good springboard to get you going :) – Brian Jun 25 '14 at 18:21

3 Answers3

1

You need to pull JSON using AJAX.

This will require you to have web server running, as some browsers, e.g. Chrome will block requests to local resources. Also have in mind that AJAX & JSON request will work only within the same domain (same origin policy), or you will have to use JSONP.

If you can use jQuery (hence it's an easiest way), look here: http://api.jquery.com/jquery.getjson/

$.getJSON( "test.json", function( data ) {
  $.each( data, function( key, val ) {
    // do something
  });
});

Hope it helps!

Karol
  • 7,803
  • 9
  • 49
  • 67
1

I see that you didn't include the tag, so I'll provide a couple of vanilla javascript solutions:

  1. If the file is located at an accesible directory, you can pull the data like this:

    Define your JSON object as follows:

    Original:

    [{ "name" : "John", "date" : "01-27-2014"  }]
    

    Modified into javascript:

    var data = '[{ "name" : "John", "date" : "01-27-2014"  }]';
    

    And save it to a plain text document named mydata.json.js, for example (the double extension has nothing to do with the content itself).

    So it becomes a valid javascript file and you can load it on your html like this:

    <script src="mydata.json.js"></script>
    

    And you can use your data var on your HTML normally.

  2. Or use this if you don't have the document locally or the above approach is too makeshifty for you. Refer to this question. Quoting:

    function loadJSON(path, success, error)
    {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function()
        {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                if (success) {
                    success(JSON.parse(xhr.responseText));
                } else {
                    if (error)
                        error(xhr);
                }
            }
        };
        xhr.open("GET", path, true);
        xhr.send();
    }
    

    Call it as:

    loadJSON('my-file.json',
        function(data) { console.log(data); },
        function(xhr) { console.error(xhr); }
    );
    

    Update:

    You can create a global var, e.g. data, to store the retrieved JSON and redefine the function as follows:

    if (xhr.readyState === 4 && xhr.status === 200) {
        data = JSON.parse(xhr.responseText); // This now contains the JSON object.
    }
    

    Note that xhr.responseText is the raw JSON string and the JSON.parse(…) functions returns a javascript collection with the data of that JSON.

Community
  • 1
  • 1
arielnmz
  • 8,354
  • 9
  • 38
  • 66
  • I really like this answer (number 1) but this is a pre-existing json file (not made by me, I think I should add) and while I was able to add the .js extension I'm unsure how to add the **var data = '[{...}]' ** parameter. – Isa Jun 25 '14 at 18:46
  • @Isa Just surround your entire JSON string with quotes `'` or double quotes `"` to make them strings and assign them to the `data` var, check my updated answer. – arielnmz Jun 25 '14 at 19:10
  • I'm sorry, I don't understand how to do this. My code needs to be able to use the json file without me needing to go in a manipulate the actual .json file. How do I add the variable (for lack of a better word) remotely? – Isa Jun 25 '14 at 23:30
  • Sorry, now I understand. In that case your best bet is to retrieve the file using the REST approach (the second solution) but the file needs to be located under the same domain or in the same server. – arielnmz Jun 25 '14 at 23:33
  • I'm still having trouble making this work. How would I then call the information stored within the json file? Is it now stored within the "data" variable? If you could do pseudo code with the code for the html table I would really appreciate it. – Isa Jun 26 '14 at 18:30
  • Thank you so much! I've been teaching myself about five different languages in the past three weeks and I would be so lost without this site. – Isa Jun 26 '14 at 23:08
0

You can do this without the need for ajax by using a server side language such as PHP. You can include the raw JSON into a Javascript variable.

Below is an example of including the file with PHP:

<script>

    //JSON included via PHP
    var books = <?php include('books.json'); ?>;

</script>

The file "books.json" would contain your raw JSON information:

{ "Pascal" : [ 
      { "Name"  : "Pascal Made Simple", "price" : 700 },
      { "Name"  : "Guide to Pascal", "price" : 400 }
   ],                       
   "Scala"  : [
      { "Name"  : "Scala for the Impatient", "price" : 1000 }, 
      { "Name"  : "Scala in Depth", "price" : 1300 }
   ]    
}
zachzurn
  • 2,161
  • 14
  • 26
  • How would I then call the objects? "books.pascal.name" ? In other words, does PHP change the formatting in anyway? (Really new, here. Sorry) – Isa Jun 26 '14 at 00:12
  • PHP will not alter your file, it will include the file as-is. You will be able to access the JSON object as you would any javascript object. – zachzurn Jul 01 '14 at 18:46