On this page

Reference

Basic Usage

Usage of laminas-json involves using two public static methods: Laminas\Json\Json::encode() and Laminas\Json\Json::decode().

// Decode a JSON value to PHP:
$phpNative = Laminas\Json\Json::decode($encodedValue);

// Encode a PHP value to JSON:
$json = Laminas\Json\Json::encode($phpNative);

ext/json

By default, the above two calls will proxy to the json_decode() and json_encode() functions of ext/json, which is bundled in default installations of PHP. Using laminas-json, however, ensures that the functionality works regardless of whether or not the extension is available. Additionally, the component provides some features not found in ext/json, such as encoding native JSON expressions, communicating class inheritance, and customizations around pretty printing.

Pretty-printing JSON

Sometimes, it may be hard to explore JSON data generated by Laminas\Json\Json::encode(), since it has no spacing or indentation. In order to make it easier, Laminas\Json\Json allows you to pretty-print JSON data in the human-readable format with Laminas\Json\Json::prettyPrint().

// Encode it to return to the client:
$json = Laminas\Json\Json::encode($phpNative);
if ($debug) {
    echo Laminas\Json\Json::prettyPrint($json, array('indent' => ' '));
}

The second, optional, argument to Laminas\Json\Json::prettyPrint() is an option array. Option indent allows providing an indentation string; by default, it uses four spaces.

Found a mistake or want to contribute to the documentation? Edit this page on GitHub!