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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With