A production-ready PHP library for parsing JSONC (JSON with Comments) format with drop-in compatibility for json_decode().
- Single-line comments (
//) and multi-line comments (/* */) - Trailing commas in objects and arrays
- Drop-in replacement for
json_decode() - Edge case handling: Preserves strings with comment syntax, escaped characters, Unicode
- Security hardening: UTF-8 BOM removal, null byte prevention, unclosed string/comment validation
- Zero dependencies: Uses native PHP JSON extension
- Well tested: 100+ tests with 100% code coverage
composer require otar/jsonc// Use global function wrapper
$data = jsonc_decode($jsonc, true);
// Check for errors using native PHP functions
if (json_last_error() !== JSON_ERROR_NONE) {
echo json_last_error_msg();
}use Otar\JSONC;
$jsonc = '{
// This is a comment
"name": "John Doe",
"age": 30,
"hobbies": [
"reading",
"coding", // Inline comment
],
}';
$data = JSONC::decode($jsonc, true);
// ['name' => 'John Doe', 'age' => 30, 'hobbies' => ['reading', 'coding']]use Otar\JSONC;
$jsonc = '{/* comment */"key": "value",}';
$json = JSONC::parse($jsonc);
// '{"key": "value"}'
// Now you can use with standard json_decode
$data = json_decode($json, true);Decodes a JSONC string. Drop-in replacement for json_decode().
public static function decode(
string $jsonc,
?bool $associative = null,
int $depth = 512,
int $flags = 0
): mixedParses JSONC string and returns cleaned JSON string (without comments and trailing commas).
public static function parse(string $jsonc): stringGlobal function alias for JSONC::decode().
The library uses native PHP error functions:
$invalidJsonc = '{invalid json}';
$result = JSONC::decode($invalidJsonc);
if ($result === null && json_last_error() !== JSON_ERROR_NONE) {
echo 'Parse error: ' . json_last_error_msg();
}- PHP 8.1 or higher
- JSON extension (enabled by default in PHP)
# Run tests
composer test
# Run tests with coverage
composer test-coverageMIT License - see LICENSE file for details.
Contributions are welcome! Please ensure all tests pass (composer test) and maintain code coverage.
Inspired by existing JSONC parsers and the need for a robust, production-ready PHP implementation with proper edge case handling.
- microsoft/node-jsonc-parser - Official JSONC parser for Node.js
- VS Code - Uses JSONC for configuration files