开发者

How to read JSON file with Dojo

How to read JSOn files 开发者_如何转开发with Dojo ?


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.


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).


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

    });


You can make use of dojo/request module :

 <script>
    require(["dojo/request", function(request){
        request("patho/to/file.json" , {handleAs :"json"}).then(function(result){/*success*/} , function(err){/*Oops!*/})

    }); 
 </script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜