Last active
December 19, 2015 12:39
-
-
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
This file contains hidden or 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
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