This weekend I released an open-source JSON5 parser for PHP!
JSON5 is a JS-compatible extension to JSON which allows comments, trailing commas, single-quoted strings, and more:
{
foo: 'bar',
while: true,
this: 'is a \
multi-line string',
// this is an inline comment
here: 'is another', // inline comment
/* this is a block comment
that continues on another line */
hex: 0xDEADbeef,
half: .5,
delta: +10,
to: Infinity, // and beyond!
finally: 'a trailing comma',
oh: [
"we shouldn't forget",
'arrays can have',
'trailing commas too',
],
}
- Fully supports UTF-8
- Supports the assoc flag, maximum depth, and converting big ints to strings
- Is tested against the official spec tests
Installation / Usage
Simply install the library using Composer:
composer require colinodell/json5
This package adds a json5_decode()
function which is a drop-in replacement for PHP's built-in json_decode()
:
$json = file_get_contents('foo.json5');
$arr = json5_decode($json);
It takes the same exact parameters as json_decode()
in the same order. This means you can upgrade your code to support JSON5 by doing a simple find-and-replace!
If you'd still like to avoid this global function, feel free to call the static Json5Decoder::decode()
method instead. (json5_decode()
simply proxies to this method for your convenience)
Additionally, there's a json5
executable you can use to convert JSON5 to plain JSON via the command line:
json5 file.json5 > file.json
Feedback
If you end up using this in your project I'd love to hear about it! Simply drop a comment below or ping me on Twitter.
Happy coding!
Enjoy this article?
Support my open-source work via Github or follow me on Twitter for more blog posts and other interesting articles from around the web. I'd also love to hear your thoughts on this post - simply drop a comment below!