Hacker News new | past | comments | ask | show | jobs | submit login

You can write a parser that generates an AST node for comments and then pretty prints that AST. So it’s not impossible, but it does require that your parser gives you the option to not just drop comments on the floor.



Alright, here's a JSON5 text:

  {
    // start
    x: "y",
    // the following is foo
    foo: "hey",
      // the following is bar
    bar: "there"
    // end
  }
When parsing it, should I attach each comment to the following name or the previous name?

If I reformat to change indentation, should I change the indentation of the comments too? How would the comment that reads "the following is bar" be re-indented?

What if there are duplicate names? JSON does allow duplicates. If I attach comments to preceding (or following) names, then while parsing I find a dup... what should I do with the preceding comment and the new name?


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.


> 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.


Don’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.


But pretty-printing is not all that one does with JSON. If that were all one ever did with JSON then JSON wouldn't exist.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: