Skip to content

Instantly share code, notes, and snippets.

@kuratowsky
Created May 22, 2012 08:27
Show Gist options
  • Select an option

  • Save kuratowsky/2767585 to your computer and use it in GitHub Desktop.

Select an option

Save kuratowsky/2767585 to your computer and use it in GitHub Desktop.
JSON Stringify - Convert JSON to String with the same JSON structure
function stringify(obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"'+obj+'"';
return String(obj);
}
else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n]; t = typeof(v);
if (t == "string") v = '"'+v+'"';
else if (t == "object" && v !== null) v = stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment