3 ms·
You make the comment a child node of the object literal node, don’t associate it with the following key/value pair at all. When you pretty print it, it will hav
by fiddlerwoaroof 3y ago
You make the comment a child node of the object literal node, don’t associate it with the following key/value pair at all. When you pretty print it, it will have the same relative order with the following kv pair as it had originally (and you cannot reorder json keys safely because the handling of duplicate keys is implementation-defined).
As far as indentation goes, if I were writing a pretty printer, I’d make indentation handled by the object/array node not by the comment/kv pair node. So that doesn’t matter: the comment will start printing at whatever the current column is just like the kv pairs would.
Anyways, among other tools, prettier has already solved this problem.
- cryptonector 3y ago> You make the comment a child node of the object literal node, don’t associate it with the following key/value pair at all. When you pretty print it, it will have the same relative order with the following kv pair as it had originally (and you cannot reorder json keys safely because the handling of duplicate keys is implementation-defined). Many implementations parse objects into hash tables and lose duplicates and even order of appearance of name/value pairs, and all of that is allowed. Such implementations will not be able to keep relative order of comments.
- fiddlerwoaroof 3y agoDon’t use that sort of implementation for a pretty printer is my point. I’m not saying you can pretty print json that has been parsed by a generic parser, but that you can write a parser that can pretty print arbitrary json.
- cryptonector 3y agoBut pretty-printing is not all that one does with JSON. If that were all one ever did with JSON then JSON wouldn't exist.