Skip to content

Instantly share code, notes, and snippets.

@ephys
Last active September 27, 2016 22:15
Show Gist options
  • Save ephys/42320cbd9dd337cbfd3283f0fc2d12a0 to your computer and use it in GitHub Desktop.
Save ephys/42320cbd9dd337cbfd3283f0fc2d12a0 to your computer and use it in GitHub Desktop.
// Remove comments from JSON with this JavaScript RegExp
// Only strips out /* */ style comments
const stripJsonRegExp = /(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)\/\*(.|\n)*?\*\/(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)/gm;
// Usage:
const commentedJson = String.raw`
/* test 1 */
{ /* test2 */
/* test2 /* test2 */
"item_b": "oh hi, \" /* test3 */", /* test6 */
/* test3 */ "item_a": "/* test4 */"
/* test5 */
/*
* multiline
*/
}
`;
const cleanJson = commentedJson.replace(stripJsonRegExp, '');
JSON.parse(cleanJson); // yay!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment