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)
Update:
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.
I'm surprised nobody mentioned json5
{
  // comments
  unquoted: 'and you can quote me on that',
  singleQuotes: 'I can use "double quotes" here',
  lineBreaks: "Look, Mom! \
No \\n's!",
  hexadecimal: 0xdecaf,
  leadingDecimalPoint: .8675309, andTrailing: 8675309.,
  positiveSign: +1,
  trailingComma: 'in objects', andIn: ['arrays',],
  "backwardsCompatible": "with JSON",
}
                        You can use the following function to decode commented json:
function json_decode_commented($json, $assoc = false, $maxDepth = 512, $opts = 0) {
  $data = preg_replace('~
    (" (?:\\\\. | [^"])*+ ") | \# [^\v]*+ | // [^\v]*+ | /\* .*? \*/
  ~xs', '$1', $data);
  return json_decode($json, $assoc, $maxDepth, $opts);
}
It supports all PHP-style comments: /*, #, //. String values are preserved as is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With