Skip to content

Getting started

Greg Bowler edited this page Apr 21, 2026 · 2 revisions

Installation

Install the package with Composer:

composer require phpgt/json

Note

If you are using WebEngine, this package is already installed as part of the framework.

Your first JSON object

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"));

Other builder methods

fromJsonDecoded()

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

fromFile()

Use this to read JSON from disk.

$json = $builder->fromFile(__DIR__ . "/example.json");

If the file does not exist, a FileNotFoundException is thrown.

fromAssociativeArray()

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"],
]);

Builder options

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).

Decode failures

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.

Clone this wiki locally