How to read JSOn files with Dojo ?
4 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.
-
1You didn't close the require. You need to add ");" in the end of your code.– LaurenceOct 24, 2012 at 11:40
-
-
How can I add my context path in 'dojo/text!/path/to/data.json' when I give the file name in require? Something like this: location.pathname.replace(/\/[^/]*$/, '').– coder247Mar 26, 2016 at 9:23
-
Example to access the "config" folder at the current level:
'dojo/text!./config/config.json
– MycahMar 3, 2018 at 0:20
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>