← All posts

PHP json_validate(): check a string is valid JSON without decoding it (PHP 8.3+)

How PHP 8.3's json_validate() works, when it beats json_decode(), when it wastes a parse, and a tested JSON_THROW_ON_ERROR pattern for real input.

Ian Croasdell giving a thumbs-up at his laptop with his tabby cat Simba curled up beside him

"Is this valid JSON?" sounds like a question PHP should have answered years ago. Until PHP 8.3 the usual trick was to call json_decode(), then check json_last_error(), and quietly build an array you never wanted. PHP 8.3 added a function that answers the question directly: json_validate(). It came from the json_validate RFC and is documented on the PHP manual page.

The signature

```php json_validate(string $json, int $depth = 512, int $flags = 0): bool ```

It returns true or false. It never gives you the data back. If the answer is false, json_last_error() and json_last_error_msg() tell you what went wrong.

A tested example

```php <?php declare(strict_types=1);

$inputs = [ '{"job": "hang curtain pole", "hours": 3}', '{"job": "hang curtain pole", "hours": 3,}', '[1, 2, 3]', '"just a string"', '', ];

foreach ($inputs as $raw) { if (json_validate($raw)) { echo "valid: {$raw}\n"; } else { echo "invalid: {$raw} (" . json_last_error_msg() . ")\n"; } } ```

Output:

```text valid: {"job": "hang curtain pole", "hours": 3} invalid: {"job": "hang curtain pole", "hours": 3,} (Syntax error) valid: [1, 2, 3] valid: "just a string" invalid: (Syntax error) ```

Three lessons in five lines:

  • Trailing commas are not allowed in JSON, even though PHP arrays accept them.
  • A bare string, number, true, false or null is valid JSON. Valid only means "well formed", not "the shape I expected".
  • An empty string is invalid, with a syntax error.

Where json_validate() earns its place

The manual's point is memory: json_validate() doesn't build the array or object, so it uses less memory than json_decode() when you don't need the payload. Good uses:

  • Checking a webhook body is well formed before saving it untouched to a queue or log.
  • A validation rule that only needs yes or no, with decoding done later elsewhere.
  • Large payloads you're passing on rather than reading.

Where it wastes a parse

The manual also warns against calling json_validate() right before json_decode(). json_decode() already validates while it decodes, so doing both parses the string twice. If you're going to use the data, decode once and make failures loud with JSON_THROW_ON_ERROR:

```php <?php declare(strict_types=1);

function readJob(string $raw): array { try { $data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR); } catch (JsonException $e) { throw new InvalidArgumentException('Bad JSON: ' . $e->getMessage()); }

if (!is_array($data) || !isset($data['job'])) { throw new InvalidArgumentException('JSON is valid, but it is not a job'); }

return $data; }

foreach (['{"job": "fix gate"}', '"null"', '{"job":'] as $raw) { try { $job = readJob($raw); echo "ok: {$job['job']}\n"; } catch (InvalidArgumentException $e) { echo "error: {$e->getMessage()}\n"; } } ```

Output:

```text ok: fix gate error: JSON is valid, but it is not a job error: Bad JSON: Syntax error ```

Notice the middle case. "null" (a JSON string) is perfectly valid JSON, so only the shape check catches it. Validation of syntax and validation of meaning are two different jobs.

The small print

  • PHP 8.3 or newer only. On 8.2 the function doesn't exist. Security support for PHP 8.2 ends on 31 December 2026 (see php.net supported versions), and I've covered the move in PHP 8.2 end of life: check your version.
  • Flags: the only flag accepted at the moment is JSON_INVALID_UTF8_IGNORE.
  • UTF-8 only: the manual notes it only works with UTF-8 encoded strings.
  • Depth: must be greater than 0. Nesting deeper than $depth makes it return false.

The habit behind it

Check what comes in from outside, decode it once, and turn it into proper types straight away, such as an enum for a status field (see backed enums: from() vs tryFrom()). That habit runs right through my book, PHP Done The Correct Way: paperback on Amazon UK or Kindle, with a free companion code page.

Need a hand with your PHP site? Have a look at PHP AIR.

Let's talk More posts