Fastest way to check if a string is JSON in PHP?

Fastest way to check if a string is JSON in PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

The Cost of json_decode in Validation Logic

The proposed solution using is_string, is_object, and is_array after json_decode is functionally correct but architecturally expensive. It relies on the PHP engine to parse a potentially massive string into an object or array just to immediately discard that data structure. This approach triggers the full JSON parser, which allocates memory for the resulting tree structure before you even check if it exists.

The primary bottleneck here is the json_decode() call itself. When you pass a 1MB text file containing non-JSON content to this function, PHP must still read the entire buffer, validate the syntax up to the first error token (or the end of the string), and construct an internal representation. Only after this heavy lifting completes does the is_object() check return false. You are paying the cost of parsing every single time you need a boolean result.

Using json_last_error for Validation

A more efficient strategy avoids object construction entirely by leveraging the error reporting mechanism built into the parser. Instead of decoding to an object, decode to an associative array or a scalar, then inspect the global state variable $json_last_error. This allows you to bail out early without creating memory overhead for invalid inputs.

Here is a refined implementation:

function isJson($string) {
    if (!is_string($string)) {
        return false;
    }

    // Attempt to decode without specifying the second argument (associative array)
    $decoded = @json_decode($string);

    // Check if an error occurred during parsing
    return json_last_error() === JSON_ERROR_NONE;
}

The critical detail here is the use of the error suppression operator @ combined with json_last_error(). By default, json_decode returns false on failure. However, distinguishing between "successfully decoded to a scalar value (e.g., 'true' or '123')" and "failed to parse" is impossible if you only check the return value of the function itself.

The @ operator suppresses the PHP error that would normally be thrown for invalid JSON syntax. After decoding, $decoded will hold either the parsed data (if valid) or false (if invalid). The global variable $json_last_error holds the specific reason why parsing failed if it did. If it equals JSON_ERROR_NONE, the string is guaranteed to be valid JSON.

Handling Edge Cases with Scalars

A common pitfall in this logic is handling JSON scalar values. In PHP, json_decode('true') returns the boolean true. If you rely solely on checking if the result is an object or array, you might incorrectly classify a valid JSON string containing just a primitive value as invalid.

Using json_last_error() solves this ambiguity. Whether the parsed output is an object, an array, a string, a number, a boolean, or null, the error code remains JSON_ERROR_NONE. This makes the function robust against inputs like "null", "123", or "hello", which are all valid JSON documents.

Performance Implications

While checking $json_last_error is faster than constructing objects and then destroying them, it does not eliminate the parsing cost. The parser still runs to validate syntax. If your use case involves streaming data or extremely high-frequency checks on massive payloads where even partial parsing is unacceptable, this method has limits.

However, for standard application logic—validating API request bodies, checking config files, or sanitizing user input—this approach offers the best balance of speed and accuracy available in standard PHP. It avoids memory allocation for invalid data and provides a clear signal via error codes rather than relying on ambiguous return values.

If you are working within the Laravel ecosystem, you might find similar utility needed when validating request payloads before processing them. While Laravel provides helper methods like request()->isJson(), understanding the underlying mechanism helps when writing raw scripts or performance-critical gateways where framework overhead is undesirable. For those deep-dive scenarios, referencing resources like LaravelCompany can provide additional context on handling JSON in PHP applications effectively.

Our network