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
Frequently Asked Questions
How do I parse JSON in PHP?▾
Use json_decode($json, true) to get an associative array, or json_decode($json) to get a stdClass object. Check json_last_error() to detect failures.
What does the second argument to json_decode() do?▾
Passing true returns an associative array. The default (false/null) returns a stdClass object. For most use cases, true is easier to work with.
How do I pretty-print JSON in PHP?▾
Pass the JSON_PRETTY_PRINT flag to json_encode(): json_encode($data, JSON_PRETTY_PRINT). Combine flags with |: JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE.
How do I handle Unicode in PHP JSON encoding?▾
By default, json_encode() escapes non-ASCII characters. Add JSON_UNESCAPED_UNICODE to preserve them: json_encode($data, JSON_UNESCAPED_UNICODE).
How do I check for JSON errors in PHP?▾
Call json_last_error() after json_encode() or json_decode(). Compare the return value to JSON_ERROR_NONE. Use json_last_error_msg() for a human-readable message.
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 →If jsondecode.com saved you time, share it with your team
Free forever. No ads. No sign-up. Help other developers find it.