JSON Reference
JSON reference. Two functions cover everything — flags do the heavy lifting.
Functions
| Function | Returns |
|---|---|
json_encode($value, $flags = 0, $depth = 512) | JSON string or false. |
json_decode($json, $assoc = false, $depth = 512, $flags = 0) | Mixed. |
json_last_error() / json_last_error_msg() | Last error / human-readable string. |
JsonException | Thrown if you pass JSON_THROW_ON_ERROR. |
JsonSerializable interface | Class can choose its own JSON shape via jsonSerialize(). |
Flags
| Flag | Effect |
|---|---|
JSON_PRETTY_PRINT | Indented output. |
JSON_UNESCAPED_SLASHES | Don't escape /. |
JSON_UNESCAPED_UNICODE | Keep Unicode literal. |
JSON_THROW_ON_ERROR | Throw JsonException instead of returning false. |
JSON_FORCE_OBJECT | Emit {} for empty arrays. |
JSON_NUMERIC_CHECK | Strings that look numeric become numbers. |
JSON_PARTIAL_OUTPUT_ON_ERROR | Don't fail on unserialisable values. |
JSON_OBJECT_AS_ARRAY | (decode) Same as passing $assoc = true. |
Type mapping
| JSON | PHP (encode) | PHP (decode w/ $assoc = true) |
|---|---|---|
| object | assoc array | assoc array |
| array | indexed array | indexed array |
| string | string | string |
| number | int / float | int / float |
| true / false | bool | bool |
| null | null | null |
Common pitfalls
- Empty PHP array
[]encodes to[]; if you wanted{}, use(object) []orJSON_FORCE_OBJECT. - Float precision —
json_encode(0.1 + 0.2)emits0.30000000000000004. - Resources, closures, and PDOStatement can't be encoded.
- Decoding deep structures may hit
$depth— bump it for big payloads.
Tip: Always pass
JSON_THROW_ON_ERROR. Old code that checks === false after a JSON call almost always forgets to check, which is exactly the bug that bites in production.Example
Example
<?php
echo json_encode(['ok' => true]), PHP_EOL;
print_r(json_decode('{"ok":true}', true));
Try it Yourself »
Exercise
Recommended flag for safer error handling.
json_encode($x, JSON
_)
snake_case; 14 chars.
Discussion
Loading…