Skip to content

Instantly share code, notes, and snippets.

@wjcrowcroft
Forked from millermedeiros/json.js
Created October 6, 2011 05:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wjcrowcroft/1266562 to your computer and use it in GitHub Desktop.
Save wjcrowcroft/1266562 to your computer and use it in GitHub Desktop.
RequireJS plugin for loading JSON files
/*!
* RequireJS plugin for loading JSON files
* - depends on Text plugin and it was HEAVILY "inspired" by it as well.
*
* IMPORTANT: it only works on r.js optimizer after version 0.26+ 20011/09/27
*
* @author Miller Medeiros
* @version 0.0.1 (2011/06/10)
* Released under the WTFPL <http://sam.zoy.org/wtfpl/>
*/
define(['text'], function(text){
var jsonParse = (typeof JSON !== 'undefined' && typeof JSON.parse === 'function')? JSON.parse : function(val){
return eval('('+ val +')'); //quick and dirty
},
buildMap = {};
//API
return {
load : function(name, req, onLoad, config) {
// Append '.json' if no filename given:
if (name.indexOf('.') < 0) {
name += ".json"
}
text.get(req.toUrl(name), function(data){
if (config.isBuild) {
buildMap[name] = data;
onLoad(data);
} else {
onLoad(jsonParse(data));
}
});
},
//write method based on RequireJS official text plugin by James Burke
//https://github.com/jrburke/requirejs/blob/master/text.js
write : function(pluginName, moduleName, write){
if(moduleName in buildMap){
var content = buildMap[moduleName];
write('define("'+ pluginName +'!'+ moduleName +'", function(){ return '+ content +';});\n');
}
}
};
});
@wjcrowcroft
Copy link
Author

Just for the use case in our app, it made sense that paths without '.json' needed to have it appended:

// Effectively changes this:
define([
    "json!api/screens.json",
    "json!api/user.json",

// to this:
define([
    "json!api/screens",
    "json!api/user",

Only really for aesthetics and I don't like seeing 'json' repeated so many times..

Use with care though, as with any method of appending filetypes.

NB: typo in #22, should read "...if no filetype given"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment