PHP › JSON Handling in PHP
How can PHP objects implementing the JsonSerializable interface customize exactly how they are converted into JSON when passed to json_encode?
IntermediateAnswer
The JsonSerializable interface requires implementing a single method, jsonSerialize, which returns the exact data structure that should actually be used when json_encode processes an instance of that class, letting you control precisely what gets included in the resulting JSON, such as excluding a sensitive password property or renaming certain fields, rather than json_encode simply dumping every public property of the object by default.
class User implements JsonSerializable {
public function __construct(private string $name, private string $password) {}
public function jsonSerialize(): mixed {
return ['name' => $this->name];
}
}
echo json_encode(new User('Ali', 'secret123'));Real-world example A User class implements JsonSerializable to explicitly exclude the password property from ever appearing in JSON output, providing a strong guarantee against accidentally leaking sensitive data through an API response regardless of how that object gets encoded.