-
-
Notifications
You must be signed in to change notification settings - Fork 1
Getting started
Install the package with Composer:
composer require phpgt/jsonNote
If you are using WebEngine, this package is already installed as part of the framework.
JSONObjectBuilder is the main entry point. It reads JSON and returns the right subtype of JSONObject.
use GT\Json\JSONObjectBuilder;
$builder = new JSONObjectBuilder();
$json = $builder->fromJsonString('{"name":"Cody", "active":true}');
echo $json->getString("name"), PHP_EOL;
var_dump($json->getBool("active"));Use this when json_decode() has already been called somewhere else.
$decoded = json_decode('{"name":"Cody"}');
$json = $builder->fromJsonDecoded($decoded);This method accepts:
- decoded objects
- associative arrays
- indexed arrays
- strings
- integers
- floats
- booleans
null
Use this to read JSON from disk.
$json = $builder->fromFile(__DIR__ . "/example.json");If the file does not exist, a FileNotFoundException is thrown.
Use this when the starting point is already a PHP associative array and you want a JSONObject.
$json = $builder->fromAssociativeArray([
"name" => "Ada",
"roles" => ["developer", "reviewer"],
]);The constructor accepts two optional arguments:
$builder = new JSONObjectBuilder(
depth: 512,
flags: JSON_BIGINT_AS_STRING,
);depth is passed to json_decode().
flags are combined with JSON_THROW_ON_ERROR, so JSON decoding errors are always surfaced as exceptions.
One useful flag is JSON_BIGINT_AS_STRING, which avoids very large integers being converted to floats.
Note
Depending on your computer's processor type, the maximum number possible to be stored inside an integer is stored in the PHP_INT_MAX constant. On 64 bit computers, this is 9,223,372,036,854,775,807 (2^63 − 1).
Malformed JSON throws JSONDecodeException.
try {
$builder->fromJsonString('{ "broken": ');
}
catch(\GT\Json\JSONDecodeException $exception) {
echo $exception->getMessage();
}Next, read Types and getters to see what kind of object the builder returns and how to read values from it.
PHP.GT/Json is a separately maintained component used by PHP.GT/WebEngine.