Skip to content
GreenSnippets

Decode JSON safely in PHP

Parse JSON with exceptions on error and a depth limit, instead of silently getting null.

PHP
<?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.