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>');
} 
4
  • 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. Commented Mar 23, 2012 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 Commented Mar 23, 2012 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... Commented Mar 23, 2012 at 12:05
  • 3
    Convince him to use jQuery and $.getJSON. It will save you both a lot of trouble and time! Commented Mar 23, 2012 at 12:07

4 Answers 4

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); }
);
Sign up to request clarification or add additional context in comments.

5 Comments

I think you forgot "error" as the third parameter for the method. And thanks for the example, I'll be using it.
@DennisS, thanks for pointing that out. I'll fix the code sample.
why is xhr.send() needed on the very last line?
@ayjay, the send() function actually sends the request, optionally with any content for the body (depending upon the HTTP method.)
How do I get the data value out of this?
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...

3 Comments

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.
@MarkDuiker: Ehm no, if I were to give you another website that refers to the 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... ;-)
@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.
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.

6 Comments

but how do i store a external file to that var myJSON? i am a real newbe :)
@Toby Create another file and include it into your page using a <script> tag before the other code that uses it.
@JamWaffles hehe that too :-P
@JamWaffles: That and this answer are the most improper use of JSON, welcome to the world of overhead!
@TobyJustus: Here you get a good example of how you are introducing overhead that jQuery doesn't have, hence you end up with a slower solution. Tons of people are using jQuery because it is a fast library, why wouldn't you?
|
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.