Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read JSON file with Dojo

Tags:

dojo

How to read JSOn files with Dojo ?

like image 247
Damir Avatar asked Mar 15 '11 11:03

Damir


3 Answers

In Dojo 1.8+, to load a JSON file (not as XHR), use dojo/text to load the file, then dojo/json to parse it. Like so:

require( [ 'dojo/json', 'dojo/text!/path/to/data.json' ], 
    function( JSON, data )
{
    var data = JSON.parse( data );
} );

Not the "!" after dojo/text, used to specify the file to load.

like image 155
voidstate Avatar answered Oct 16 '22 22:10

voidstate


This is a bit of a broad question.

If you mean, how do you make a server request and have it automatically treated as JSON on the way back, you'd do something like this:

dojo.xhrGet({
    url: "your/server/endpoint/here",
    handleAs: "json",
    load: function(obj) {
        /* here, obj will already be a JS object deserialized from the JSON response */
    },
    error: function(err) {
        /* this will execute if the response couldn't be converted to a JS object,
           or if the request was unsuccessful altogether. */
    }
});

Note handleAs: "json" above, which tells dojo.xhrGet (or xhrPost, etc.) to attempt to convert the response to a JS object before firing the load callback.

http://dojotoolkit.org/reference-guide/dojo/xhrGet.html

Individually, if you already have yourself a JSON string and just need to convert it to a JS object, Dojo has dojo.fromJson(str) for this (and dojo.toJson(obj) for the other direction).

like image 14
Ken Franqueiro Avatar answered Oct 16 '22 22:10

Ken Franqueiro


With dojo 1.8: Add the Module ID "dojo/request/xhr" to your dependencies and xhr as callback argument, then:

xhr("path/to/file.json", {
        handleAs: "json"
    }).then(function(obj){
        // do something with the obj            
    }, function(err){
        // Handle the error condition

    }, function(evt){
        // Handle a progress event from the request if the
        // browser supports XHR2

    });
like image 1
intA Avatar answered Oct 16 '22 20:10

intA