Skip to content

Instantly share code, notes, and snippets.

@anmarco
Last active March 20, 2023 19:20
Show Gist options
  • Save anmarco/b3fb81e0456134653783aced6dbf7f8b to your computer and use it in GitHub Desktop.
Save anmarco/b3fb81e0456134653783aced6dbf7f8b to your computer and use it in GitHub Desktop.
A function that takes crappy invalid json and returns a valid one (y)
const sanitizeJSON = function (badJSON) {
return badJSON
.replace(/:\s*"([^"]*)"/g, function(match, p1) {
return ': "' + p1.replace(/:/g, '@colon@') + '"';
})
.replace(/:\s*'([^']*)'/g, function(match, p1) {
return ': "' + p1.replace(/:/g, '@colon@') + '"';
})
.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?\s*:/g, '"$2": ')
.replace(/@colon@/g, ':')
.replace("\\'", "@singlequotes@")
.replace(/(')/g, '"')
.replace(/(@singlequotes@)/, "'")
;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment