JSON in PHP — json_decode, json_encode & Error Handling
PHP has built-in JSON support via json_encode() and json_decode(). No extensions or packages are required.
Parse JSON with json_decode()
json_decode() returns a stdClass object by default. Pass true as the second argument to get an associative array instead.
<?php
$json = '{"name":"Alice","age":30,"active":true}';
// As object (default)
$obj = json_decode($json);
echo $obj->name; // Alice
// As associative array
$arr = json_decode($json, true);
echo $arr['name']; // AliceEncode to JSON with json_encode()
json_encode() converts a PHP value to a JSON string. Use JSON_PRETTY_PRINT for readable output.
<?php
$data = ['name' => 'Alice', 'age' => 30, 'active' => true];
$json = json_encode($data);
// {"name":"Alice","age":30,"active":true}
$pretty = json_encode($data, JSON_PRETTY_PRINT);
echo $pretty;Handle encoding and decoding errors
Check json_last_error() after calling json_encode() or json_decode().
<?php
$result = json_decode('invalid json', true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo 'JSON error: ' . json_last_error_msg();
// JSON error: Syntax error
}JSON API response
A standard pattern for returning JSON from a PHP endpoint.
<?php
header('Content-Type: application/json');
$response = ['status' => 'ok', 'data' => ['id' => 1, 'name' => 'Alice']];
echo json_encode($response);Related Tools
JSON in Other Languages
Format and validate your JSON instantly
Free, no ads, no sign-up. Also converts JSON to TypeScript, YAML, CSV, and more.
Open JSON Formatter →