PHP JSON
JSON (JavaScript Object Notation) is the language web services use to exchange data. A JavaScript front end, a mobile app and a PHP back end can all read and write it. PHP converts between its own values and JSON text with two functions: json_encode() and json_decode().
PHP values and JSON values
| PHP | JSON |
|---|---|
int, float |
number |
string |
string (always UTF-8) |
true / false |
true / false |
null |
null |
list array [1, 2, 3] (keys 0, 1, 2…) |
array [1,2,3] |
associative array ['a' => 1] |
object {"a":1} |
| object (public properties) | object |
PHP decides between a JSON array and a JSON object by looking at the keys: only an array whose keys are exactly 0, 1, 2, … becomes a JSON array.
Encoding: PHP → JSON
<?php
$product = [
'id' => 17,
'name' => 'Green tea',
'price' => 3.5,
'inStock' => true,
'tags' => ['drink', 'hot'],
'supplier'=> null,
];
echo json_encode($product) . PHP_EOL;
// A list becomes a JSON array, but gaps in the keys make it an object
echo json_encode([10, 20, 30]) . PHP_EOL;
echo json_encode([1 => 'a', 2 => 'b']) . PHP_EOL;
echo json_encode([]) . PHP_EOL;
echo json_encode(new stdClass()) . PHP_EOL;{"id":17,"name":"Green tea","price":3.5,"inStock":true,"tags":["drink","hot"],"supplier":null}
[10,20,30]
{"1":"a","2":"b"}
[]
{}
Formatting flags
The second argument of json_encode() takes flags, combined with |:
| Flag | Effect |
|---|---|
JSON_PRETTY_PRINT |
Line breaks and 4-space indentation |
JSON_UNESCAPED_UNICODE |
Write ă instead of ă |
JSON_UNESCAPED_SLASHES |
Write / instead of \/ |
JSON_THROW_ON_ERROR |
Throw JsonException instead of returning false |
JSON_FORCE_OBJECT |
Always produce objects, even for lists |
JSON_PRESERVE_ZERO_FRACTION |
Keep 10.0 instead of 10 |
<?php
$city = ['name' => 'Đà Nẵng', 'url' => 'https://example.test/da-nang', 'temp' => 31.0];
echo json_encode($city) . PHP_EOL;
echo json_encode($city, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION) . PHP_EOL;
echo json_encode($city, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;{"name":"\u0110\u00e0 N\u1eb5ng","url":"https:\/\/example.test\/da-nang","temp":31}
{"name":"Đà Nẵng","url":"https://example.test/da-nang","temp":31.0}
{
"name": "Đà Nẵng",
"url": "https://example.test/da-nang",
"temp": 31
}
Decoding: JSON → PHP
json_decode($json) returns objects of class stdClass by default. Pass true as the second argument to get associative arrays, which is what most PHP code prefers:
<?php
$json = '{"order": 1042, "customer": {"name": "Lan", "vip": true},
"items": [{"sku": "TEA-01", "qty": 2}, {"sku": "CUP-07", "qty": 1}]}';
$asObject = json_decode($json);
echo $asObject->customer->name . PHP_EOL;
$data = json_decode($json, true);
echo "Order #{$data['order']} for {$data['customer']['name']}" . PHP_EOL;
$units = 0;
foreach ($data['items'] as $item) {
echo "- {$item['sku']} x {$item['qty']}" . PHP_EOL;
$units += $item['qty'];
}
echo "Units: $units" . PHP_EOL;
var_dump($data['customer']['vip']);Lan
Order #1042 for Lan
- TEA-01 x 2
- CUP-07 x 1
Units: 3
bool(true)
Handling invalid JSON
When the input is broken, json_decode() returns null — which is also what valid JSON null decodes to! The reliable approach is the JSON_THROW_ON_ERROR flag together with try/catch:
<?php
$inputs = ['{"ok": true}', '{"ok": tru}', "{'single': 'quotes'}", 'null'];
foreach ($inputs as $text) {
try {
$value = json_decode($text, true, 512, JSON_THROW_ON_ERROR);
echo "valid: " . var_export($value, true) . PHP_EOL;
} catch (JsonException $e) {
echo "invalid: " . $e->getMessage() . PHP_EOL;
}
}
var_dump(json_validate('[1, 2, 3]'), json_validate('[1, 2,'));valid: array (
'ok' => true,
)
invalid: Syntax error
invalid: Syntax error
valid: NULL
bool(true)
bool(false)
json_validate() (PHP 8.3+) only checks the syntax, without building the PHP value — useful for large payloads.
Note: JSON strings must use double quotes. Single quotes, trailing commas and comments are all invalid JSON.
Controlling how objects are encoded
By default only public properties are encoded. Implement the JsonSerializable interface to decide exactly what an object turns into:
<?php
class Money implements JsonSerializable
{
public function __construct(private int $cents, private string $currency) {}
public function jsonSerialize(): array
{
return ['amount' => $this->cents / 100, 'currency' => $this->currency];
}
}
$response = ['status' => 'ok', 'total' => new Money(1999, 'USD')];
echo json_encode($response, JSON_PRETTY_PRINT) . PHP_EOL;{
"status": "ok",
"total": {
"amount": 19.99,
"currency": "USD"
}
}
Tip: A PHP API endpoint typically finishes with
header('Content-Type: application/json'); echo json_encode($data, JSON_THROW_ON_ERROR);.
Test yourself
What does json_encode(['a' => 1, 'b' => 2]) produce?
[1,2]{"a":1,"b":2}["a","b"]a=1&b=2
How do you make json_decode() return associative arrays instead of stdClass objects?
- Pass
trueas the second argument - Use
JSON_PRETTY_PRINT - Call
json_array() - Cast the JSON string to array
Why is checking json_decode($s) === null not a reliable error check?
json_decodenever returnsnull- The valid JSON text
nullalso decodes tonull - It only works in PHP 7
- It throws instead