PHP JSON
PHP has two functions that cover most JSON needs — json_encode and json_decode. Both ship with the standard library.
Encode
PHP
$user = ['name' => 'Ada', 'roles' => ['admin', 'dev']];
echo json_encode($user);
// {"name":"Ada","roles":["admin","dev"]}
echo json_encode($user, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
Decode
PHP
$json = '{"name":"Ada","age":36}';
$obj = json_decode($json); // -> stdClass object
$arr = json_decode($json, true); // -> associative array
echo $obj->name; // Ada
echo $arr['name']; // Ada
Useful flags
| Flag | Effect |
|---|---|
JSON_PRETTY_PRINT | Indented output. |
JSON_UNESCAPED_SLASHES | Don't escape /. |
JSON_UNESCAPED_UNICODE | Keep emoji and Unicode literal. |
JSON_THROW_ON_ERROR | Throw JsonException instead of returning false. |
JSON_FORCE_OBJECT | Emit {} for empty arrays instead of []. |
JSON_NUMERIC_CHECK | Numeric strings encoded as numbers. |
Error handling
PHP
try {
$data = json_decode($input, true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo 'Bad JSON: ', $e->getMessage();
}
Custom objects with JsonSerializable
PHP
class User implements JsonSerializable {
public function __construct(public string $name, private string $secret) {}
public function jsonSerialize(): array {
return ['name' => $this->name]; // skip the secret
}
}
echo json_encode(new User('Ada', 'shh')); // {"name":"Ada"}
Tip: Default to
$assoc = true when decoding into something you'll iterate. The stdClass shape forces awkward -> access for what's really a hash map.Example
Example
<?php $user = ['name' => 'Ada', 'roles' => ['admin', 'dev']]; $json = json_encode($user, JSON_PRETTY_PRINT); echo $json, PHP_EOL; print_r(json_decode($json, true));Try it Yourself »
Exercise
Encode a value to JSON.
($user);
Snake_case; 11 chars.
Discussion
Loading…