How to determine whether a string is valid JSON?

How to determine whether a string is valid JSON?

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

Stefan Bogdanescu

Founder & Senior Architect

How to determine whether a string is valid JSON?

When you need to validate incoming data, the instinct to avoid external dependencies is strong. Running a raw string through an online validator like JSONLint feels safe because it handles every edge case from the latest RFC updates, but in a production environment, sending sensitive payloads over the network just to check their syntax is inefficient and introduces latency. You need a solution that runs locally, is fast, and correctly identifies malformed structures before your application attempts to parse them.

In PHP, the most robust approach leverages the built-in json_decode function with its error reporting flag enabled. This method avoids third-party libraries entirely while utilizing the engine's native parser, which adheres to strict JSON specification requirements. The key lies in understanding that json_decode returns null on success and a boolean false on failure, but only if you explicitly pass true as the second argument to trigger error logging.

function isJson(string $string): bool {
    // Enable JSON_ERROR_REPORT to catch syntax errors
    json_last_error($string); 
    
    // Attempt decoding with true to populate json_last_error()
    $decoded = json_decode($string, true);

    // Check if the last error was successful (0)
    return json_last_error() === JSON_ERROR_NONE;
}

However, relying solely on json_decode requires careful attention to the state of the global error context. The json_last_error() function returns a constant representing the type of error encountered during the most recent decode attempt. If no error occurred, it returns JSON_ERROR_NONE. This pattern is reliable because it directly inspects the result of the parsing operation rather than guessing based on string length or content inspection.

One common pitfall involves empty strings or strings containing only whitespace. While technically valid JSON (representing an empty object or array), some legacy parsers might treat them differently depending on how they were constructed. The json_decode function handles these cases gracefully, returning an empty array or null as appropriate, and setting the error code to JSON_ERROR_NONE. This ensures your validation logic doesn't accidentally reject valid, albeit empty, data structures.

Another consideration is the strictness of the JSON standard itself. PHP's implementation follows the ECMA-404 specification, which differs slightly from older implementations regarding trailing commas or single quotes. By using json_last_error(), you catch issues like JSON_ERROR_SYNTAX_ERROR immediately. This prevents your application from crashing downstream when trying to cast a malformed string into an object.

If you are working within the Laravel ecosystem, this pattern integrates seamlessly with service containers or helper functions without requiring additional packages. The principle remains the same: validate syntax before parsing. Attempting to access properties on a string that isn't valid JSON will result in fatal errors later in the request lifecycle. By front-loading this check, you ensure that only well-formed data proceeds to business logic layers.

For high-throughput applications where function call overhead is a concern, you might consider caching the validation state if the same strings are processed repeatedly. However, for most general use cases, the native PHP functions provide sufficient performance without the complexity of external requests or custom parsers. The trade-off here is simplicity and speed versus the absolute certainty of an online tool; in local execution, certainty is just as high because the underlying parser is identical to what validates the JSON on your server.

Ultimately, using json_decode with error reporting is the industry-standard way to handle this problem in PHP. It is lightweight, requires no additional dependencies, and leverages the language's core capabilities to ensure data integrity before it touches your application logic.

Our network