Skip to content

Instantly share code, notes, and snippets.

@pseudosavant
Last active March 13, 2018 00:45
Show Gist options
  • Save pseudosavant/e7c7a59f96e6071ed30cfcf6bfe9e5fd to your computer and use it in GitHub Desktop.
Save pseudosavant/e7c7a59f96e6071ed30cfcf6bfe9e5fd to your computer and use it in GitHub Desktop.
JSON with comments POC. Example here: http://jsbin.com/favarow/
// jshint esnext:true
/*
Every JSON entry is removed if the key is "_comment". "_comment" can optionally be followed
by underscores, letters, or digits to make the key more unique (e.g. "_comments_name", "_comments_todo").
The JSON is still valid JSON with the "_comment", and it will parse fine anywhere. It will
just have the extra "_comment" entries.
See example here: http://jsbin.com/favarow/
*/
const o = {
"configurationVersion": 2.1, "_comment": "this value is rarely changed",
"clientID": "X918273645",
"customerReferenceID": "000392739",
"network": {
"ipAddresses": ["17.128.255.0", "127.0.0.1", "10.10.10.1"],
"_comment_abc_123": "Only the 17.x.x.x address is publicly addressable",
"ports": [80, 443, 21, 22, 1337]
},
"processingLevel": "FULL",
"customer": {
"name": "john doe",
"postalCode": "A1B2C3",
"country": "CAN",
"_comment": "Canada is the best"
},
"misc": {
"_comment": "\
Are backslash line-breaks actually valid JSON? \
bar \
baz \
foo \
"
}
};
const noComments = commentFreeJson(o);
console.log(`No comments found in output: ${testCommentsFound(noComments)}`);
console.log(noComments);
function commentFreeJson(obj) {
const commentRe = /(,?\s?"_comment[\w\d_]*"\s?:\s?"[^"]{0,}?"\s?)/gi;
return JSON.stringify(obj).replace(commentRe, '');
}
function testCommentsFound(s) {
return /_comment/.test(s) === false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment