Skip to content

JSONDocument

Greg Bowler edited this page Apr 21, 2026 · 1 revision

JSONDocument is a small helper for building JSON output one property at a time.

It is particularly useful when the response shape is assembled gradually, or when error responses need a consistent structure.

Building a document

use GT\Json\Schema\JSONDocument;

$document = new JSONDocument();
$document->set("name", "Ada");
$document->set("role", "Developer");

echo $document;

Output:

{"name":"Ada","role":"Developer"}

Nested keys

Dot notation creates nested objects for us.

$document = new JSONDocument();
$document->set("department.name", "Computer Science");
$document->set("department.building", "Babbage");

Output:

{"department":{"name":"Computer Science","building":"Babbage"}}

get() also understands dot notation:

echo $document->get("department.name");

If we ask for a simple key whose value is itself an object, get() returns another JSONDocument, so nested access can continue naturally.

Starting from an existing JSONObject

JSONDocument can also wrap a JSONObject.

use GT\Json\JSONObjectBuilder;
use GT\Json\Schema\JSONDocument;

$builder = new JSONObjectBuilder();
$json = $builder->fromAssociativeArray([
	"name" => "Ada",
	"skills" => ["PHP", "SQL"],
]);

$document = new JSONDocument($json);
echo $document;

Error responses

error() clears any existing properties and replaces them with an error payload.

$document = new JSONDocument();
$document->error("Something went wrong");

echo $document;

Output:

{"error":"Something went wrong"}

An optional context array can be included:

$document->error(
	"Validation failed",
	context: ["field" => "email"]
);

Output:

{"error":"Validation failed","errorContext":{"field":"email"}}

You can rename both property names if required:

$document->error(
	"Validation failed",
	context: ["field" => "email"],
	property: "message",
	contextProperty: "details"
);

After error() has been called, later calls to set() throw JSONErrorStateException.

Error callbacks

If you need to log or react to errors as they are set, attach a callback:

$document->setErrorCallback(function(string $message, ?array $context):void {
	error_log($message);
});

The callback runs each time error() is called.

Using JSONDocument in WebEngine

When a WebEngine route uses the JSON view, the framework creates a JSONDocument as the view model. That means page logic can work directly with methods such as:

  • set()
  • get()
  • error()
  • setErrorCallback()

The JSON output is then handled by WebEngine's response pipeline.

Outside WebEngine, JSONDocument is still just a normal PHP object and can be used anywhere a stringable JSON payload is useful.


Next, read JSON Schema if you need to validate JSON against a predefined schema before using it.

Clone this wiki locally