Skip to content

Instantly share code, notes, and snippets.

@achudars
Last active December 19, 2015 12:39
Show Gist options
  • Save achudars/5956264 to your computer and use it in GitHub Desktop.
Save achudars/5956264 to your computer and use it in GitHub Desktop.
Converts JavaScript strings into proper JSON without the usage of eval(). This is an awesome function found here: http://stackoverflow.com/questions/4781226/convert-converted-object-string-to-json-or-object/4781447#4781447
function preprocessJSON(str) {
return str.replace(/("(\\.|[^"])*"|'(\\.|[^'])*')|(\w+)\s*:/g,
function(all, string, strDouble, strSingle, jsonLabel) {
if (jsonLabel) {
return '"' + jsonLabel + '": ';
}
return all;
});
}
// usage: data = JSON.parse(preprocessJSON(json));
// in case you stumble upon single quoted strings, be sure to use: data.replace(/'/g, '"')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment