Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Standard PHP Library and Classes

The JsonSerializable interface

Reference for the PHP JsonSerializable interface: control what json_encode() outputs for your objects with jsonSerialize(), hide fields and nest objects.

By default json_encode() turns an object into a JSON object made of its public properties. That is rarely what you want for domain classes with private state, computed values or dates. JsonSerializable hands you control: implement jsonSerialize() and return whatever should be encoded in the object's place.

The returned value can be an array, a scalar, null, or another object (which is serialized in turn, including other JsonSerializable objects).

PHP
class Tag implements JsonSerializable
{
    public function __construct(private string $name) {}

    public function jsonSerialize(): mixed
    {
        return ['name' => $this->name];
    }
}

Try it

PHP Hiding fields and adding computed ones

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Without the interface, and returning a scalar

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
interface JsonSerializable
{
    public function jsonSerialize(): mixed;
}
Name Description
jsonSerialize() Takes no parameters. Returns the data that json_encode() should encode instead of the object.

Return value: any value that json_encode() can encode (mixed). A list-shaped array becomes a JSON array, an associative array becomes an object.

Errors / Exceptions: exceptions thrown inside jsonSerialize() propagate out of json_encode(). Encoding failures (for example invalid UTF-8 in a returned string) follow the usual json_encode() rules; pass JSON_THROW_ON_ERROR to get a JsonException.

Usage notes

  • Used only by json_encode(). It does not affect serialize(), var_export() or var_dump().
  • It decides the shape. Return an empty array and you get [], not {}. Return new stdClass or use JSON_FORCE_OBJECT when you need an empty object.
  • Nested objects are visited. If the returned array contains other JsonSerializable objects, their jsonSerialize() runs too.
  • Return plain data. Returning arrays, scalars or other objects is fine; avoid handing back an object that leads straight back to this one, which would loop.
  • Without the interface, only public properties are encoded, as the second example shows. Typed properties that are uninitialized are skipped.
  • Backed enums encode as their scalar value automatically; no interface is needed.
  • Dates: a DateTimeInterface encodes as an object with date, timezone_type and timezone. Return $date->format(DATE_ATOM) yourself for something friendlier.
  • Decoding is separate. json_decode() gives arrays or stdClass; rebuild your classes with a named constructor.