Decode JSON safely in PHP
Parse JSON with exceptions on error and a depth limit, instead of silently getting null.
- PHP
- GreenSnippets
- MIT
- Executed with PHP 8.2
<?php
/** @throws InvalidArgumentException when the payload is not valid JSON */
function decodeJson(string $json, int $depth = 32): mixed
{
try {
return json_decode($json, true, $depth, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
throw new InvalidArgumentException('Invalid JSON: ' . $e->getMessage(), 0, $e);
}
}How it works
json_decode returns null both for the JSON value null and for invalid input, which hides errors. JSON_THROW_ON_ERROR turns failures into a JsonException. A depth limit protects against deeply nested payloads, and true returns associative arrays.
Related snippets
- PHP Tested
Retry a callable with exponential backoff in PHP
Re-run flaky operations with growing delays and jitter, only for chosen exception types.
- TypeScript Tested
Typed fetch helper that checks the response
A fetch wrapper that throws on HTTP errors and validates the JSON body with a type guard.
- JavaScript Tested
Verify a webhook signature in Node.js
Validate an HMAC-SHA256 webhook against the raw request body with a constant-time comparison and replay window.
- JavaScript Tested
Retry an async operation with exponential backoff
Retry a failing promise-returning function with growing, jittered delays and a retry predicate.

