April 25, 2011

Introducing JSON Lite

Thankfully, as of PHP 5.2 there are built-in functions for converting between PHP objects and JSON. But, as we’ve all experienced sometimes you need to support people stuck in the past. Without further adieu, I introduce JSON Lite.

Get JSON Lite from GitHub.

Benchmark

To compare speed with the popular JSON libraries available I setup a very simple benchmark. The contenders include:

Setup

Each library was setup to encode a PHP array to JSON 50 times, then convert it back to a PHP array 50 times.

Results PHP to JSON

Results JSON to PHP

Benchmark Code Excerpts

// test array
$php_test = array(
    'numbers' => array(234234, 345345, 345245, 234234),
    'strings' => array('!@#$%^&*()_+', '{}|\?><:', 'asasdd'),
    'special' => array(true, false, null, 0, '0'),
    'hashes' => array('key1' => 'a', 'key2' => 'b', 'key3' => 'c'),
    '!@#$%^&*)(_){}[]' => 'weird key'
);

// Native PHP Methods
$json_str = json_encode($php_test);
$php_arr = json_decode($json_str, true);

// PEAR JSON Lib
$pear_obj = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
$json_str = $pear_obj->encode($php_test);
$php_arr = $pear_obj->decode($json_str);

// Jsonrpc
$value = php_jsonrpc_encode($php_test);
$json_str = $value->serialize();
$value = php_jsonrpc_decode_json($json_str);
$php_arr = php_jsonrpc_decode($value);

// JSON Lite
$json_str = json_lite::to_json($php_test);
$php_arr = json_lite::from_json($json_str, FALSE);

Final Thoughts

It should be noted that JSON Lite is the only library in group that produced a slightly different, although fully valid, JSON string.

JSON Lite produced:

{"numbers":[234234,345345,345245,234234],
"strings":["!@#$%^&*()_+","\u007b\u007d|\\?><:","asasdd"],
"special":[true,false,null,0,0],
"hashes":{"key1":"a","key2":"b","key3":"c"},
"!@#$%^&*)(_)\u007b\u007d\u005b\u005d":"weird key"}

The others librarys produced:

{"numbers":[234234,345345,345245,234234],
"strings":["!@#$%^&*()_+","{}|\\?><:","asasdd"],
"special":[true,false,null,0,"0"],
"hashes":{"key1":"a","key2":"b","key3":"c"},
"!@#$%^&*)(_){}[]":"weird key"}

So, JSON Lite is faster than the other libraries because it makes some tradeoffs in how it encodes JSON strings and is limited to creating PHP arrays from JSON strings it created. Hopefully you will find it useful for PHP to PHP process communication / RPC calls or for exporting from PHP to other JSON parsers and APIs.