/php-json-comment

Lightweight JSON comment and trailing comma stripper library for PHP

Primary LanguagePHPMIT LicenseMIT

adhocore/json-comment

Latest Version Travis Build Scrutinizer CI Codecov branch StyleCI Software License Donate 15 Donate 25 Donate 50 Tweet

  • Lightweight JSON comment stripper library for PHP.
  • Makes possible to have comment in any form of JSON data.
  • Supported comments: single line // comment or multi line /* comment */.
  • Also strips trailing comma at the end of array or object, eg:
    • [1,2,,] => [1,2]
    • {"x":1,,} => {"x":1}
  • Handles literal LF (newline/linefeed) within string notation so that we can have multiline string

Installation

composer require adhocore/json-comment

# for php5.6
composer require adhocore/json-comment:^0.2

Usage

use Ahc\Json\Comment;

// The JSON string!
$someJsonText = '{"a":1,
"b":2,// comment
"c":3 /* inline comment */,
// comment
"d":/* also a comment */"d",
/* creepy comment*/"e":2.3,
/* multi line
comment */
"f":"f1",}';

// OR
$someJsonText = file_get_contents('...');

// Strip only!
(new Comment)->strip($someJsonText);

// Strip and decode!
(new Comment)->decode($someJsonText);

// You can pass args like in `json_decode`
(new Comment)->decode($someJsonText, $assoc = true, $depth = 512, $options = JSON_BIGINT_AS_STRING);

// Or you can use static alias of decode:
Comment::parse($json, true);

# Or use file directly
Comment::parseFromFile('/path/to/file.json', true);

Example

An example JSON that this library can parse:s

{
  "name": "adhocore/json-comment",
  "description": "JSON comment stripper library for PHP.
    There is literal line break just above this line but that's okay",
  "type":/* This is creepy comment */ "library",
  "keywords": [
    "json",
    "comment",
    // Single line comment, Notice the comma below:
    "strip-comment",
  ],
  "license": "MIT",
  /*
   * This is a multiline comment.
   */
  "authors": [
    {
      "name": "Jitendra Adhikari",
      "email": "jiten.adhikary@gmail.com",
    },
  ],
  "autoload": {
      "psr-4": {
          "Ahc\\Json\\": "src/",
      },
  },
  "autoload-dev": {
      "psr-4": {
          "Ahc\\Json\\Test\\": "tests/",
      },
  },
  "require": {
      "php": ">=7.0",
      "ext-ctype": "*",
  },
  "require-dev": {
      "phpunit/phpunit": "^6.5 || ^7.5 || ^8.5",
  },
  "scripts": {
      "test": "phpunit",
      "echo": "echo '// This is not comment'",
      "test:cov": "phpunit --coverage-text",
  },
}