-
-
Notifications
You must be signed in to change notification settings - Fork 1
Home
This library provides a consistent way to read, inspect and construct JSON data in PHP without falling back to loosely typed arrays and stdClass objects.
It builds on PHP.GT/DataObject by adding JSON-specific functionality, so the JSON objects we work with are immutable and expose type-safe getters such as getString() and getInt().
-
JSONObjectBuilder, which turns JSON strings, decoded JSON values and files intoJSONObjectinstances -
JSONKvpObjectfor JSON objects with named properties -
JSONPrimitivesubtypes for root JSON values such as strings, numbers, booleans,nulland arrays -
JSONDocument, which helps build JSON responses and nested keys -
Validator,ValidationSuccessandValidationErrorfor JSON Schema validation
This package can be used on its own in any PHP project.
If you are using WebEngine, the integration point to know about is JSONDocument. WebEngine uses it as the view model for JSON responses, so page logic can call methods like set() and error() and let the framework output the final document.
use GT\Json\JSONObjectBuilder;
use GT\Json\JSONKvpObject;
use GT\Json\JSONPrimitive\JSONPrimitive;
$builder = new JSONObjectBuilder();
$json = $builder->fromJsonString('{"id": 105, "tags": ["php", "json"]}');
if($json instanceof JSONKvpObject) {
echo $json->getInt("id"), PHP_EOL;
echo implode(", ", $json->getArray("tags", "string")), PHP_EOL;
}
elseif($json instanceof JSONPrimitive) {
var_dump($json->getPrimitiveValue());
}JSONObjectBuilder decides which JSON type has been decoded and returns the matching object. We can then read the data through getters rather than manually checking each value ourselves.
Start with Getting started to install the package and decode a few different kinds of JSON.
PHP.GT/Json is a separately maintained component used by PHP.GT/WebEngine.