Introducing colinodell/json5: a UTF-8 compatible JSON5 parser for PHP

This weekend I released an open-source JSON5 parser for PHP!

JSON5 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',
    ],
}

This PHP implementation:

  • 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?

About Colin O'Dell

Colin O'Dell

Colin O'Dell is a Senior Software Engineer at SeatGeek. In addition to being an active member of the PHP League and maintainer of the league/commonmark project, Colin is also a PHP docs contributor, conference speaker, and author of the PHP 7 Migration Guide.