25

I am writing some code in JavaScript. In this code i want to read a json file. This file will be loaded from an URL.

How can I get the contains of this JSON file in an object in JavaScript?

This is for example my JSON file located at ../json/main.json:

{"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]}

and i want to use it in my table.js file like this:

for (var i in mainStore)
{       
    document.write('<tr class="columnHeaders">');
    document.write('<td >'+ mainStore[i]['vehicle'] + '</td>');
    document.write('<td >'+ mainStore[i]['description'] + '</td>');
    document.write('</tr>');
} 
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
Rick Weller
  • 1,258
  • 9
  • 35
  • 54
  • I understand that by "reading a json file" you mean making the request to the url that returns json content. If so, then can you explaing why don't you want to use jQuery for that? It has $.ajax function that is perfectly suitable for this. – Michal B. Mar 23 '12 at 12:00
  • hey Michal, that is what i want to do yes. Why i dont want to use jQuery is because the person i am working for doesn't want it because he is afraid of the speed of the script. Not my call to make – Rick Weller Mar 23 '12 at 12:04
  • @TobyJustus: Proper profiling would tell you that jQuery is not any slower regarding getJSON; all he is doing is making it way to hard on himself, at the gain of almost nothing. In fact, Stroustrup did a nice talk on how native code can even be slower than libraries made for you... – Tamara Wijsman Mar 23 '12 at 12:05
  • 3
    Convince him to use jQuery and $.getJSON. It will save you both a lot of trouble and time! – Michal B. Mar 23 '12 at 12:07

5 Answers5

50

Here's an example that doesn't require jQuery:

function loadJSON(path, success, error)
{
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function()
    {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            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); }
);
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
1

XHR can be used to open files, but then you're basically making it hard on yourself because jQuery makes this a lot easier for you. $.getJSON() makes this so easy to do. I'd rather want to call a single line than trying to get a whole code block working, but that's up to you...

Why i dont want to use jQuery is because the person i am working for doesn't want it because he is afraid of the speed of the script.

If he can't properly profile native VS jQuery, he shouldn't even be programming native code.

Being afraid means he doesn't know what he is doing. If you plan to go for performance, you actually need to know how to see how to make certain pieces of code faster. If you are only just thinking that jQuery is slow, then you are walking into the wrong roads...

Tamara Wijsman
  • 12,198
  • 8
  • 53
  • 82
  • 3
    Perhaps he's talking about avoiding the 100ms it will take to get a cdn copy of jquery, fetch a json file and then parse it? I'd rather get the json file and jquery in parallel. – Mark Duiker Mar 08 '16 at 20:12
  • 1
    @MarkDuiker: Ehm no, if I were to give you another website that refers to the http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js script it would only take ~3ms to read it from your cache as you are currently reading a website that refers to the very same script and you have likely visited quite a few other websites referring to it as well in the past days. That's part of the purpose of a CDN... ;-) – Tamara Wijsman Mar 08 '16 at 22:32
  • @Tom Wijsman years late but... Because there are programs like Adobe which allows scripting for their apps and only javascript can be used. That is one case were you coudn't use jquery. – FabricioG Aug 30 '18 at 18:58
0
function loadDoc() {
    const xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
       console.log(xhttp.responseText)
      }
    };
    xhttp.open("GET", "./user.json");
    xhttp.send();
  }

Naming using the linux filename structure You can store the responseText to a variable or whatever you want to do with it

0

JSON has nothing to do with jQuery.

There is nothing wrong with the code you have now.


To store the variable mainStore, it is a variable in that json.

You should store that json to a variable:

var myJSON = {"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]};

var mainStore = myJSON.mainStore;

//.. rest of your code.
Naftali
  • 144,921
  • 39
  • 244
  • 303
0

I understand that by "reading a json file" you mean making the request to the url that returns json content. If so, then can you explain why you don't want to use jQuery for this purpose? It has $.ajax function that is perfectly suitable for this and covers the browsers' differences.

If you want to read the file then you have to do it server-side, e.g. php and provide it somehow to the dom (there are different methods) so js can use it. Reading file from disk with js is not possible.

Michal B.
  • 5,676
  • 6
  • 42
  • 70