Skip to content

Instantly share code, notes, and snippets.

@josue
Created December 12, 2010 08:02
Show Gist options
  • Save josue/737923 to your computer and use it in GitHub Desktop.
Save josue/737923 to your computer and use it in GitHub Desktop.
Converts javascript strings to simple JSON.
String.prototype.trim = function() { return this.toString().replace(/^\s+/,'').replace(/\s+$/,''); };
String.prototype.ToJSON = function() {
var quotes = function(s) { return (s||'').toString().replace(/^"/,'').replace(/"$/,'').replace(/^'/,'').replace(/'$/,'').trim(); };
var commas = function() {
this.change = function(s){
var s = (s||'').toString();
if(/.*:.*/.test(s) && /('.*,.*')/.test(s)) {
var x = s.match(/('.*,.*')/)[1] || ''; var orig = x; var n = x.match(/,/g).length;
for(i=1; i<=n; i++) {
x = x.replace(/,/,'_#_');
}
s = s.replace(orig,x);
}
return s;
};
this.back = function(s){
return (s||'').toString().replace(/_#_/g,',');
};
return this;
};
var json = null;
var str = this.toString().trim().replace(/'/g,"").replace(/"/g,"'").trim();
if(str.match(/\{.*:.*\}/)) {
str = str.replace(/^\{/,'').replace(/\}$/,'');
var keyval = commas().change(str).split(',') || null;
if(keyval && keyval.length>0) {
json = {};
for(x in keyval) {
var KV = keyval[x].trim().trim(), re1 = /(.*):(.*?:.*)/, re2 = /(.*):(.*)/;
var K = KV.match(re1) ? KV.match(re1)[1] : KV.match(re2)[1];
var V = KV.match(re1) ? KV.match(re1)[2] : KV.match(re2)[2];
if(K && V) {
K = quotes(K), V = quotes(V);
json[K] = V.match(/\{.*\}/) ? V.ToJSON() : commas().back(V);
}
}
}
}
return json;
};
/*
* Josue Rodriguez <josue@josuerodriguez.com>
*
* Converts strings to simple JSON.
*
* var json = "{total:44}".ToJSON();
*
* var json = '{show:files, test:{text:"OH, hi, i can haz my cheeseburger nao plz, spanks"}, inception:{level:6}}'.ToJSON();
*
* [Warning] Has not been fully tested, except for the above. May break on double quotes and deep level hierarchy.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment