Basel Shishani Basel Shishani - 6 months ago 48
JSON Question

A JSON parser for PHP that supports comments

Can anyone suggest a JSON parser that allows any kind of comments, with PHP bindings - need the comments badly for config files but json_decode doesn't support them.

(I am aware of: 1. other format such as YAML, 2. comments are not part of the standard)


Why don't we use:

  • YAML: Benchmarks show it's slower - and we might want to send the data over the wire - not sure if YAML is best for that.

  • XML: too verbose - simple human editing is a requirement. And no need for the extended features of XML.

  • INI: there is hierarchy and nesting of variable depth in the data. And we need a ubiquitous format as the data might be distributed with apps or work with apps in other languages.

  • Pre-processing: data can be contributed and shared by users, tough to impose a requirement to pre-process before adding data to an app.


If you need portability and don't want any pre-processing to fixup non-standard components, then YAML is probably the way to go.

Most, if not all, of JSON is compatible with YAML (YAML is a superset of JSON), and it supports comments.

For a recent project I felt the need to move away from .ini for our "default settings" file - so that we no longer had to convert some strings to integers or booleans afterwards (since parse_ini_file parses values as strings, foo=1 or foo=true are both string values).

JSON seemed like a good format, but it didn't support comments. If you want to make this work, however, I would recommend not implementing (or using) a separate JSON parser altogether. What I did was create a simple wrapper function that strips out the comments with a regex, and then use the native json_decode.