Skip to content

Instantly share code, notes, and snippets.

@leiming
Created September 27, 2016 07:14
Show Gist options
  • Save leiming/d3cb9a2227a9f856f957b599c12207c0 to your computer and use it in GitHub Desktop.
Save leiming/d3cb9a2227a9f856f957b599c12207c0 to your computer and use it in GitHub Desktop.
var badJSON = '{one : "1:1", two : { three: \'3:3\' }}';
var fixedJSON = 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, ':')
;
console.log('Before: ' + badJSON);
console.log('After: ' + fixedJSON);
console.log(JSON.parse(fixedJSON));
Run code snippetCopy snippet to answerExpand snippet
It produces this output:
// Before: {one : "1:1", two : { three: '3:3' }}
// After: {"one": "1:1", "two": { "three": "3:3" }}
{
"one": "1:1",
"two": {
"three": "3:3"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment