adhocore / json-comment
Lightweight JSON comment stripper library for PHP
Fund package maintenance!
adhocore
paypal.me/ji10
Installs: 465 508
Dependents: 9
Suggesters: 2
Security: 0
Stars: 31
Watchers: 2
Forks: 6
Open Issues: 1
Requires
- php: >=7.0
- ext-ctype: *
Requires (Dev)
- phpunit/phpunit: ^6.5 || ^7.5 || ^8.5
README
- 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
- Supports JSON string inside JSON string (see ticket #15 and PR #16)
- Zero dependency (no vendor bloat).
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:
{ "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", }, }