JSON is one of the most common data formats exchanged between web applications. Whether a PHP application communicates with a JavaScript frontend, a payment service, or another backend, JSON decoding is often among the first operations performed when processing a request.

Yet JSON handling is also a surprisingly common source of subtle bugs. A malformed document, an unexpected data type, or a failed encoding operation can produce behavior that is difficult to diagnose if the application does not distinguish invalid input from legitimate values.

PHP provides the necessary tools to handle these situations explicitly. The challenge is using them consistently at the application boundary.

The Problem with Silent JSON Failures

Consider a simple decoding operation:

$data = json_decode($requestBody, true);

Without exception-based error handling, json_decode() returns null when decoding fails. Unfortunately, null is also a legitimate JSON value.

Consequently, checking whether the result is null does not reliably distinguish malformed input from the valid JSON document containing only null.

PHP provides json_last_error() and json_last_error_msg() for traditional error handling. However, exception-based handling generally produces a clearer control flow.

Use JSON_THROW_ON_ERROR

The JSON_THROW_ON_ERROR flag was introduced in PHP 7.3 and remains available throughout PHP 8.

When this flag is supplied, decoding failures raise JsonException rather than relying on the traditional JSON error-state mechanism.

try {
    $data = json_decode(
        $requestBody,
        true,
        32,
        JSON_THROW_ON_ERROR
    );
} catch (JsonException $exception) {
    // Handle malformed JSON.
}

This approach separates valid input from decoding failures and makes the error-handling path explicit.

The depth argument also deserves attention. PHP’s default maximum nesting depth is 512, but most application request formats require far less nesting. A smaller limit can reject excessively nested documents earlier.

A Reusable JSON Request Decoder

Let’s create a small decoder for a JSON API endpoint. The decoder will reject malformed JSON, require a top-level object, and validate the fields expected by our application.

For this example, an API accepts a product name and a quantity.

<?php

declare(strict_types=1);

final class InvalidRequest extends RuntimeException
{
}

function decodeProductRequest(string $body): array
{
    if (strlen($body) > 65536) {
        throw new InvalidRequest('Request too large');
    }

    try {
        $data = json_decode(
            $body,
            false,
            32,
            JSON_THROW_ON_ERROR
        );
    } catch (JsonException $exception) {
        throw new InvalidRequest(
            'Malformed JSON',
            previous: $exception
        );
    }

    if (!$data instanceof stdClass) {
        throw new InvalidRequest(
            'Expected a JSON object'
        );
    }

    if (
        !property_exists($data, 'name') ||
        !is_string($data->name) ||
        trim($data->name) === ''
    ) {
        throw new InvalidRequest(
            'Invalid product name'
        );
    }

    if (
        !property_exists($data, 'quantity') ||
        !is_int($data->quantity) ||
        $data->quantity < 1 ||
        $data->quantity > 100
    ) {
        throw new InvalidRequest(
            'Quantity must be between 1 and 100'
        );
    }

    return [
        'name' => trim($data->name),
        'quantity' => $data->quantity,
    ];
}

$examples = [
    '{"name":"Keyboard","quantity":2}',
    '{"name":"Keyboard","quantity":"2"}',
    '{"name":"Keyboard",}',
    'null',
];

foreach ($examples as $json) {
    try {
        $product = decodeProductRequest($json);

        echo "Accepted: "
            . json_encode(
                $product,
                JSON_THROW_ON_ERROR
            )
            . PHP_EOL;
    } catch (InvalidRequest $exception) {
        echo "Rejected: "
            . $exception->getMessage()
            . PHP_EOL;
    }
}

The example deliberately uses strict validation. A quantity represented by the string “2” is rejected, even though PHP could convert it to an integer.

At an API boundary, silently converting input types can conceal client-side mistakes and produce inconsistent behavior.

Expected Output

Accepted: {"name":"Keyboard","quantity":2}
Rejected: Quantity must be between 1 and 100
Rejected: Malformed JSON
Rejected: Expected a JSON object

The example distinguishes four situations: valid input, an incorrect field type, malformed JSON syntax, and a valid JSON value with an unexpected top-level structure.

These are different errors and should not be treated as interchangeable.

Decoding Is Not Validation

Successfully decoding JSON only proves that the input is syntactically acceptable. It does not establish that the document follows the application’s expected schema.

For example, all of the following are valid JSON values:

null
42
"hello"
[]
{"name":"Keyboard"}

An endpoint expecting a product object must reject the first four examples, even though none necessarily contains malformed JSON.

For larger APIs, schema-validation libraries can provide reusable rules and more detailed error reporting. Nevertheless, the principle remains the same: parsing and application validation are separate responsibilities.

Be Careful with Large Integers

JSON numbers can represent values that exceed the integer range available on the running PHP platform.

PHP provides JSON_BIGINT_AS_STRING to preserve sufficiently large integer values as strings instead of converting them to floating-point numbers.

$data = json_decode(
    '{"id":9223372036854775808}',
    true,
    32,
    JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING
);

This is particularly important when processing external identifiers. An identifier should not lose precision merely because it passed through a JSON decoder.

Where identifiers are not intended for arithmetic, representing them as strings is often a sensible application-level decision.

Encoding Can Fail Too

Developers frequently focus on decoding errors while assuming that encoding application responses cannot fail.

However, json_encode() can fail when encountering unsupported values, malformed UTF-8, recursive structures, or non-finite floating-point values.

Using JSON_THROW_ON_ERROR during encoding makes these failures explicit.

$response = json_encode(
    ['status' => 'ok'],
    JSON_THROW_ON_ERROR
);

In production, encoding failures should be logged internally and translated into controlled server responses. Detailed exception messages should not automatically be exposed to API clients.

Production Considerations

A robust JSON endpoint should enforce request-body limits before decoding, validate the Content-Type header, and distinguish client errors from internal server failures.

It should also consider duplicate object keys, which JSON parsers may accept while retaining only one value. Applications requiring strict duplicate-key rejection need additional validation beyond json_decode().

The example’s string-length check protects only the decoder itself. A real HTTP server should enforce upload and request-size limits before buffering an arbitrarily large body into application memory.

Finally, exception messages intended for developers should not become part of a public API contract without deliberate design.

Conclusion

Reliable JSON handling begins with a clear distinction between syntax, structure, and application rules.

PHP’s JSON_THROW_ON_ERROR flag makes parsing failures easier to manage, but developers must still validate types, constrain resource usage, and handle encoding errors.

These practices are not complicated, yet they establish a much more predictable boundary between an application and the external systems that communicate with it.

LEAVE A REPLY

Please enter your comment!
Please enter your name here