2

Suppose there is json file but some c style comments /* ... */ have been added to increase the readability like

{
 "filename" : "alice " , /* name of the file */
 /**
   assume this case never happens "filename" : "alice /*bob*/"
 **/

  /***
    some comments
  */
  "files" : "/scratch/*"  /* it should not remove "/scratch/*" */
}

How to write a script preferably bash or python that removes the comments from the json and return the correct json like

{
   "filename":"alice ",
   "files" :  "/scratch/*"
}
Ankit Vallecha
  • 708
  • 7
  • 17
  • You could use regular expressions. – syntaxError Jun 12 '17 at 06:04
  • @rosh: No, he needs to use a parser. – T.J. Crowder Jun 12 '17 at 06:07
  • 1
    Apparently it's not clear to everyone, so could you update your question to say what should happen to `{"foo": "This is a /* test */"}`? Should it remove that, or leave it alone as it's inside a string? – T.J. Crowder Jun 12 '17 at 06:11
  • @T.J.Crowder AFAIK c-style comments are NOT part of json spec. A parser won't be able to handle it. Unless you propose to extend the syntax of json and write a new parser... – Shai Jun 12 '17 at 06:11
  • @Shai: Obviously. I didn't mean an off-the-shelf parser. I meant a customized one. – T.J. Crowder Jun 12 '17 at 06:12
  • @T.J.Crowder in that case I would vote to close as "too broad" :( – Shai Jun 12 '17 at 06:13
  • If you're flexible with what format to use, go with yaml. It supports comments, so you don't have to hack together a solution. – ronakg Jun 12 '17 at 08:37

2 Answers2

1

I suppose the advice from Douglas Crockford is appropriate here:

Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser.

ArturFH
  • 1,697
  • 15
  • 28
-1

Since JSON doesn't have C-style comments, you'll need to customize a JSON parser to handle them in the pseudo-JSON text. Crockford has two JSON parsers written in JavaScript here and the http://json.org site has a list of JSON parsers in just about any language you could want. You'll need to take one and modify it to handle the comments.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • for this case can't we write a simple script? – Ankit Vallecha Jun 12 '17 at 06:34
  • @AnkitVallecha: It won't be *simple*, but it may not be that bad. You'd have to keep track of whether you're in a string (being sure to handle escaped quotes within strings), track whether you're in a comment, etc. It might be just as simple to modify an existing JSON parser, and it would probably be more robust to modify a proper parser. (Edge cases always crop up.) But sure, you *may* be able to write a relatively short program to do it. – T.J. Crowder Jun 12 '17 at 06:38