How to use a JSON file in javascript

First you need a handle on a file. You need to get it somehow either through ajax or through server-side behaviour.

You need to tell use where the file is. How you plan to get it and what serverside code your using.

Once you have you can use JSON.parse(string) on it. You can include the json2.js file if you need to support older browsers.

If you use jQuery you can also try jQuery.parseJSON for parsing instead.

An option for remotely getting json would be using jQuery.getJSON

To load it you can either use JSONP or some kind of library with ajax functionality like jQuery.ajax or Ajax.Request. It can be done in raw javascript but that’s just ugly and re-inventing the wheel.

$.getJSON("document.json", function(data) {
    console.log(data);
    // data is a JavaScript object now. Handle it as such

});

Leave a Comment