In a task I had to write comments in JSON files and decode them using PHP. I share it. Maybe it helps someone else. The regex was tough.
Asked
Active
Viewed 298 times
0
-
3Surely if you add comments to what WAS a JSON file it is NO LONGER a JSON file as comments are not part of the JSON spec !? – RiggsFolly Sep 07 '18 at 16:46
-
Yes. That's true. Becomes something else. It is not json anymore. – András Szabácsik Sep 07 '18 at 16:54
-
So its a bit like saying how can I compile a C program when it has lines of COBOL in it ! – RiggsFolly Sep 07 '18 at 16:55
-
JSON is a machine to machine data transfer format and comments have no place in them – RiggsFolly Sep 07 '18 at 16:59
-
1I mean, this is a legitimate problem to solve - there are definitely examples of files that people intend to be JSON that contain comments. But that said, it's not one that hasn't been answered before, so posting and answering your own question just looks like you're looking for easy reputation. This isn't a site to post tutorials. – iainn Sep 07 '18 at 17:01
-
@RiggsFolly json annotation would be quite useful when I persist configurations as JSON ... i feel there is more to json than 'wire transfer format' .02 – YvesLeBorg Sep 07 '18 at 18:27
-
Why, its so delightfully simple and straightforward unlike XML – RiggsFolly Sep 07 '18 at 18:52
1 Answers
-1
Remove the comments with regular expression
$jsonStringWithComments = file_get_contents ( "jsonFileWithComments.json" );
$pattern = '/(((?<!http:|https:)\/\/.*|(\/\*)([\S\s]*?)(\*\/)))/im';
$decodedObject = json_decode ( preg_replace ( $pattern, '', $jsonStringWithComments ) );
This regular expression can capture "one-line" comments, start double slashes // or "multi-line" comments between slash asterisk /* and asterisk slash */.
With it, you can parse JSON like the following:
{
"lorem": "ipsum",
"dolor":/* inline comment */ "sit amet",
"consectetur": "adipiscing",
/*
multi
line
comment
*/
"Pellentesque": "ultrices",
//single line comment
"lectus": "nec",
"elit": "dictum",
"url": "http://example.com"
}

András Szabácsik
- 1,957
- 1
- 16
- 11