PHP JSON Decode: Safe Parsing and Encoding in Modern PHP
In modern PHP, use json_decode($json, true, 512, JSON_THROW_ON_ERROR) to parse JSON into associative arrays. The JSON_THROW_ON_ERROR flag makes decoding errors throw a JsonException. That distinguishes a valid JSON null from a malformed response that would otherwise also return null.
To encode data back into JSON, call json_encode($value, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE). This combination throws on encoding failures, keeps slashes readable in URLs, and outputs literal UTF-8 characters instead of Unicode escape sequences. For domain models and data transfer objects, implement JsonSerializable to choose the fields in the output.
The Silent Null Pitfall in json_decode()
The standard signature of json_decode() defines four parameters:
json_decode(
string $json,
?bool $associative = null,
int $depth = 512,
int $flags = 0
): mixed
By default, the fourth parameter $flags is 0. Without explicit error flags, json_decode() returns null on any syntax failure:
$result = json_decode("{invalid-json-payload");
// $result is null, but no exception is thrown
That makes error handling ambiguous when you consume an external web API. JSON allows null as a scalar value, so an endpoint might return {"data": null} or simply null to represent an empty result:
$response = json_decode("null");
// $response is null, representing valid JSON
If your code checks if ($result === null) to detect errors, it cannot tell whether the remote server returned an intentional null value or if an HTTP proxy returned an HTML error page that failed to parse.
Before PHP 7.3, developers had to inspect the global error state using json_last_error() and json_last_error_msg() immediately after every decode call:
$data = json_decode($rawPayload, true);
if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException("JSON decode error: " . json_last_error_msg());
}
The timing of that check matters. If other code runs another JSON operation without JSON_THROW_ON_ERROR before you inspect the error state, it may replace the stored error code. The archived JSON gotchas article shows invalid JSON returning null under the older default behavior.
Modern Error Handling with JSON_THROW_ON_ERROR and JsonException
PHP 7.3 introduced the JSON_THROW_ON_ERROR flag through the accepted JSON_THROW_ON_ERROR RFC. The flag applies to both json_decode() and json_encode().
When you supply JSON_THROW_ON_ERROR, a parsing error triggers a JsonException. The class extends the base Exception, as described in the PHP JsonException documentation. You can catch JSON errors separately from other failures:
<?php
$rawInput = '{"user": "Alex", "role": "admin"'; // Missing closing brace
try {
$payload = json_decode($rawInput, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
// Syntax error detected: "Syntax error" with code JSON_ERROR_SYNTAX
error_log("Failed to parse API payload: " . $e->getMessage());
throw new InvalidArgumentException("Malformed JSON received from remote provider", 0, $e);
}
With this flag, a returned null represents the JSON null literal in the payload. Invalid syntax throws instead, so you can drop the json_last_error() check.
Associative Arrays Versus stdClass Objects
The second argument of json_decode(), $associative, controls whether JSON objects become PHP objects or arrays.
Decoding as Objects (Default)
When $associative is false, JSON objects decode into instances of stdClass. The omitted argument also produces objects unless JSON_OBJECT_AS_ARRAY is set:
$json = '{"name": "Sarah", "settings": {"theme": "dark"}}';
$user = json_decode($json, false, 512, JSON_THROW_ON_ERROR);
echo $user->name; // "Sarah"
echo $user->settings->theme; // "dark"
Property access is convenient, but reading a missing stdClass property triggers an undefined property warning in modern PHP. You also need to convert objects before using standard PHP array utilities on them.
Decoding as Associative Arrays
Pass true as the second argument to decode all JSON objects into associative arrays:
$json = '{"name": "Sarah", "settings": {"theme": "dark"}}';
$user = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
echo $user["name"]; // "Sarah"
echo $user["settings"]["theme"]; // "dark"
Associative arrays are a common choice for API integrations. You can inspect keys with array_key_exists(), merge defaults with the spread operator, and safely add elements to an array as the request moves through validation layers.

Static Analysis and Type Safety
The official PHP json_decode manual documents the return type of json_decode() as mixed. A valid JSON payload can be an array, an integer, a string, a boolean, or null.
Static analysis tools like PHPStan flag operations on mixed at higher rule levels because the analyzer cannot guarantee the decoded value is an array. Check the expected shape before reading nested values:
$data = json_decode($responseBody, true, 512, JSON_THROW_ON_ERROR);
if (!is_array($data)) {
throw new UnexpectedValueException("Expected JSON object or array, got " . gettype($data));
}
// PHPStan now understands that $data is an array
$userId = $data["id"] ?? null;
For list payloads, check the type and use count() to verify the expected PHP array length before iterating over batch items.
Decoding flags for external payloads
The IETF RFC 8259 specification describes the open JSON data format. When decoding external payloads, pay attention to number sizes, nesting depth, and text encoding.
Preserving Large Integers with JSON_BIGINT_AS_STRING
RFC 8259 places no explicit limits on the size of numbers. PHP integers are bounded by PHP_INT_MAX, which is 9223372036854775807 on a typical 64-bit build.
When an API returns an integer beyond that boundary, PHP may decode it as a floating-point number and lose precision in its last digits:
$json = '{"id": 18592837465928374619}';
// Without flag: converts to float(1.8592837465928E+19), losing precision
$dataLoss = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
// With flag: preserves exact digits as a string
$safe = json_decode($json, true, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
// Result: $safe["id"] === "18592837465928374619"
Pass JSON_BIGINT_AS_STRING whenever you consume microservice identifiers or database keys that might exceed standard 64-bit integer limits.
Managing Nesting Depth
The third argument of json_decode() defines the maximum nesting depth:
$data = json_decode($json, true, 64, JSON_THROW_ON_ERROR);
The default depth is 512. Choose a smaller limit if your API contract permits it. If a payload exceeds that limit, json_decode() throws a JsonException. An invalid depth argument, such as 0, throws ValueError on PHP 8 and later.
Handling Malformed UTF-8 Sequences
JSON requires UTF-8 text. If an external service sends malformed UTF-8 bytes, json_decode() rejects the string with JSON_ERROR_UTF8. If your application needs to process the payload despite those bytes, pass JSON_INVALID_UTF8_SUBSTITUTE in PHP 7.2 and later. PHP then replaces corrupted bytes with the Unicode replacement character U+FFFD so decoding can complete.
Safe Encoding with json_encode()
Use error flags when encoding PHP values, too. The PHP json_encode manual defines its signature:
json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false
Without flags, json_encode() returns boolean false on failure, such as when processing non-UTF-8 strings or circular references. Include JSON_THROW_ON_ERROR so you can catch an exception when encoding fails.
Flags for API responses
For modern web services, combine these flags:
$data = ["url" => "https://example.com/api", "amount" => 42.0];
$flags = JSON_THROW_ON_ERROR
| JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
| JSON_PRESERVE_ZERO_FRACTION;
$json = json_encode($data, $flags);
The remaining flags control the output:
JSON_UNESCAPED_SLASHES: Leaves forward slashes (/) unescaped, making URLs easier to read in JSON text. Escaped slashes are valid JSON too; a JSON decoder produces the same URL either way. Read the response with a JSON parser, and use this flag when you want readable raw JSON.JSON_UNESCAPED_UNICODE: Encodes multibyte UTF-8 characters literally instead of converting them into Unicode escape sequences. Characters likeéandüremain legible.JSON_PRESERVE_ZERO_FRACTION: Keeps float values like42.0as42.0in the output instead of integer42. This keeps types consistent for strongly typed consumers.
Empty Arrays Versus Empty Objects
In PHP, a single array type represents both ordered lists and keyed hash maps. In JSON, lists [] and objects {} are distinct.
An empty PHP array [] encodes as a JSON array [] by default. If an external consumer expects an empty JSON object {} for one dictionary field, cast that field to an object. JSON_FORCE_OBJECT would also change other arrays in the payload:
$payload = [
"items" => [],
"metadata" => (object) [],
];
$json = json_encode($payload, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
// Result: {"items":[],"metadata":{}}
Custom Object Serialization with JsonSerializable
When you pass an object instance to json_encode(), PHP inspects its properties. By default, it serializes all public properties and skips protected or private properties.
To control this process, implement the JsonSerializable interface. The PHP JsonSerializable interface requires a single method:
<?php
namespace App\DTO;
use DateTimeImmutable;
use JsonSerializable;
final class UserResponse implements JsonSerializable
{
public function __construct(
public readonly int $id,
public readonly string $email,
public readonly DateTimeImmutable $createdAt,
private readonly string $passwordHash,
private readonly string $internalNotes,
) {}
public function jsonSerialize(): array
{
return [
"id" => $this->id,
"email" => $this->email,
"created_at" => $this->createdAt->format(DateTimeImmutable::ATOM),
];
}
}
echo json_encode(
new UserResponse(7, "alex@example.com", new DateTimeImmutable("2026-11-29T12:00:00+00:00"), "secret", "internal"),
JSON_THROW_ON_ERROR
);
The encoder uses the return value of jsonSerialize(). It can return an array, a scalar value, or another encodable value. The interface declares a mixed return type on current PHP releases; an implementation may use the narrower array return type shown above.
This gives you control over what the API exposes:
- You can leave password hashes and internal database flags out of the serialized output.
- You can convert internal PHP types like
DateTimeImmutableto standard ISO 8601 strings. - Output property names can match an API specification, such as
snake_case, while the class usescamelCaseinternally.
With property hooks in PHP 8.4, json_encode() reads public properties through their get hooks, including readable virtual properties. Use JsonSerializable when you need an explicit list of fields in API output.

Putting the checks together in a payload decoder
For HTTP responses expected to contain a JSON object or array, put the parsing and validation checks in one routine. This PHP 8.4 example rejects empty bodies and scalar JSON values:
<?php
declare(strict_types=1);
namespace App\Http;
use JsonException;
use UnexpectedValueException;
final class PayloadDecoder
{
/**
* @return array<array-key, mixed>
* @throws JsonException|UnexpectedValueException
*/
public function decodeArrayPayload(string $httpBody): array
{
// Step 1: Reject empty network responses before parsing
$trimmed = trim($httpBody);
if ($trimmed === "") {
throw new UnexpectedValueException("API returned an empty response body");
}
// Step 2: Parse strictly with error throwing and big int protection
$flags = JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING;
$decoded = json_decode($trimmed, true, 512, $flags);
// Step 3: Enforce expected array shape
if (!is_array($decoded)) {
throw new UnexpectedValueException(
"Expected JSON object or array, received " . gettype($decoded)
);
}
return $decoded;
}
}
$decoder = new PayloadDecoder();
var_export($decoder->decodeArrayPayload('{"id": 123}'));
The decoder checks the body before application code reads its values. Empty bodies and malformed JSON produce exceptions; the type check rejects scalar JSON values. Add field validation for the API schema before using the returned array.
Common Mistakes to Avoid
Assuming decoded output is always an array
Passing true as the second argument to json_decode() guarantees that JSON objects become arrays. However, if the payload is "hello" or 42, the return value is a string or integer, not an array. Always verify with is_array() before key access.
Encoding resources or circular references
PHP stream resources cannot be encoded to JSON. Passing a database connection, file handle, or circular object graph causes json_encode() to fail. With JSON_THROW_ON_ERROR, PHP throws a JsonException with "Type is not supported" or "Recursion detected". Catching that failure lets you stop before sending broken data.
Frequently Asked Questions
What happens when json_decode() receives an empty PHP string?
An empty PHP string contains no JSON text. The JSON text "", by contrast, represents a valid empty string value. Under default flags, json_decode("") returns null with json_last_error() set to JSON_ERROR_SYNTAX. When using JSON_THROW_ON_ERROR, it throws a JsonException stating "Syntax error".
How does json_decode() handle duplicate keys in an object?
According to RFC 8259, JSON object keys should be unique, but parsers may handle duplicates. In PHP, json_decode() overwrites earlier duplicate keys with later values. For example, {"status": "pending", "status": "active"} decodes with $result["status"] === "active".
Why does json_encode() turn an associative array into a list?
If an array has sequential integer keys starting at zero without gaps (0, 1, 2), PHP considers it a list and encodes it as [...]. If you remove an element with unset(), the numeric sequence breaks, and json_encode() serializes it as an object {"0": ..., "2": ...}. Use array_values() to re-index the array before encoding if you require a JSON list.
Can I pass a file or network stream directly to json_decode()?
json_decode() accepts a string, so read the response body before calling it. For a file, file_get_contents() returns a string or false; check that result before decoding. Large streams need a separate incremental parsing approach because loading the entire body into a string consumes memory.