Skip to content

Instantly share code, notes, and snippets.

@ilearnio
Last active December 13, 2015 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilearnio/ff9cae07f3df702181a9 to your computer and use it in GitHub Desktop.
Save ilearnio/ff9cae07f3df702181a9 to your computer and use it in GitHub Desktop.
fixJSON function. Removes comments and trailing commas from JSON
/**
* 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