Hacker News new | ask | show | jobs
by m463 555 days ago
There's something to be said for the hard limitations of json that made it successful.

Because of that it didn't become XML or YAML or markdown or protobufs or *RPC or microsoft config file format or all the rest. All those formats have "reasons", but they are harder to understand, harder to parse or not as portable or on and on...

(that said, I wouldn't mind comments. JUST comments).

1 comments

Most reasonable parsers has an allow-comments flag, and even in JS you could it in a simple regexp replace all with:

const obj = JSON.parse(jsonText.replaceAll(/("(?:\\"|\\.|[^"])"|[^\/])|\/\/.|(\/)/g,"$1$2"));

The above should be multiline JSON safe and give you single-line comments to end-of-line, it matches first strings (and checks for escaped double-quotes and escapes to get them correctly) or all other characters except // sequences (outside of strings) and passes that straight through via group 1(anything outside of string not starting with /) or 2(single / even if it's outside of JSON spec), if a // sequence is found it's not passed through and disappears.

Yes, regexps can be abused. This one should be fine though but only use it for config files you control :), use as CC0 and keep an keen eye if translating to another language since escapes will differ if the regexp goes into a string instead of a regexp literal like in JS.