Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A JSON parser for PHP that supports comments

Tags:

json

comments

php

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.

like image 865
Basel Shishani Avatar asked Nov 16 '11 08:11

Basel Shishani


2 Answers

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",
}
like image 90
aross Avatar answered Sep 27 '22 03:09

aross


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.

like image 26
Alexander Shostak Avatar answered Sep 27 '22 03:09

Alexander Shostak