Last active
December 13, 2015 17:17
-
-
Save ilearnio/ff9cae07f3df702181a9 to your computer and use it in GitHub Desktop.
fixJSON function. Removes comments and trailing commas from JSON
This file contains 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
/** | |
* Removes comments and trailing commas from JSON | |
*/ | |
function fixJSON(str) { | |
return str | |
// remove comments | |
.replace(/\/(?:\*{2,}\s[\s\S]+?|\*[^\*]+?)\*\/|([\s;])+\/\/.*$/gm, '') | |
// remove trailing commas | |
.replace(/,+\s*(\}|\])/g, '$1'); | |
} | |
var json_demo = ` | |
{ | |
/** | |
* This comment will be removed | |
*/ | |
"foo": 1, | |
// this one too | |
"bar": 2, // camma will be stripped, | |
"baz": [1,2,3,] | |
}`; | |
console.log(fixJSON(json_demo)); | |
// Outputs: | |
// { | |
// "foo": 1, | |
// "bar": 2, | |
// "baz": [1,2,3] | |
// } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment