json5 / json5-spec

The JSON5 Data Interchange Format
https://spec.json5.org
MIT License
50 stars 10 forks source link

Proposal to remove single-line comments #11

Closed lsloan closed 4 years ago

lsloan commented 5 years ago

When JSON5 data includes single-line comments, if the data is compacted by removing whitespace, any data that follows the comments may appear to be a comment as well. To prevent that, multiline comments could always be used, because the end of comments will be explicit. Single-line comment support could be phased out to prevent problems caused by compacting data.

jordanbtucker commented 5 years ago

Thanks for the suggestion. Rather than removing single line comments from JSON5, I think it should be the minifier's responsibility to convert single line comments to multiline comments or just remove comments completely.

// Unminified
{
  // This comment documents this property.
  message: 'Don\'t forget to pick up eggs.',
}

// Minified with comments
{/* This comment documents this property.*/message:"Don't forget to pick up eggs."}

// Minified without comments
{message:"Don't forget to pick up eggs."}
lsloan commented 5 years ago

I guess that's not unreasonable. It makes the minifier's job a little more complex than just removing whitespace.

jordanbtucker commented 5 years ago

Since the goal of a minifier is to make the payload as small as possible, this would likely include removing comments, but would also include more optimizations.

The easiest way to do this is to just round-trip the JSON5 document since JSON5 usually outputs the most efficient version by default.

const json5 = `
{
  // This comment documents this property.
  "message": 'Don\\'t forget to pick up eggs.',
  "hex": 0xDECAF,
  "dec": 123.000,
}
`

const minified = JSON5.stringify(JSON5.parse(json5))

console.log(minified) // {message:"Don't forget to pick up eggs.",hex:912559,dec:123}

Some minifiers have an option to preserve documentation comments, which are usually in the form /** Documentation goes here. */, which is a multi-line comment anyway.