Created
May 14, 2012 04:20
-
-
Save ancestral/2691775 to your computer and use it in GitHub Desktop.
Convert Wesnoth WML file into JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* wmlreader.js | |
* | |
* Read a Wesnoth WML file and parse it, save it as a JSON string. | |
* | |
* This depends on jQuery to read in the file. If you already have the file as a string | |
* you can skip readConfigFile() and just use readWML(). | |
* | |
* This isn’t quite valid JSON. It has duplicate entries. I’ll need to turn those into arrays or something. | |
* | |
* last updated 13 May 12 | |
*/ | |
function readConfigFile(title) { | |
result = ""; | |
$.ajax({ | |
url: title, | |
async: false, | |
success: function(data) { | |
result = data; | |
} | |
}); | |
return result; | |
} | |
function readWML(data) { | |
var file = data.toString().split('\n'); | |
for (var i = 0; i < file.length; i++) { | |
var that = file[i]; | |
that = that.replace(/\'/g, "\\'"); | |
that = that.replace(/\"/g, ""); | |
that = that.trim(); | |
if (that.search(/\[[_A-Za-z]+\]/) != -1) { | |
file[i] = that.replace(/[\[\]]+/g, '"'); | |
file[i] = file[i] + ': {'; | |
} else if (that.search(/\[\/[_A-Za-z]+\]/) != -1) { | |
if (file[i-1].charAt(file[i-1].length-1) == ',') { | |
file[i-1] = file[i-1].substring(0,file[i-1].length-1); | |
} | |
file[i] = '},'; | |
} else if (that.indexOf('=') != -1) { | |
that = that.split('='); | |
file[i] = '"' + that[0].trim() + '":"' + that[1].trim() + '",'; | |
} else { | |
file[i] = ''; | |
} | |
} | |
// Delete that hanging comma. (There’s probably a more elegant way to do this.) | |
if (file[file.length-2].charAt(file[file.length-2].length-1) == ',') { | |
file[file.length-2] = file[file.length-2].substring(0,file[file.length-2].length-1); | |
} | |
return '{' + file.join('') + '}'; | |
} | |
// For older browsers: | |
if (typeof String.prototype.trim != 'function') { | |
String.prototype.trim = function() { | |
return this.replace(/^\s+/, '').replace(/\s+$/, ''); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment