PHP

Safe JSON Decode (no exceptions)

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Wrap json_decode so invalid input gives you a clear false rather than a silent null. PHP 7.3+ JSON_THROW_ON_ERROR makes this cleaner — but the wrapper preserves a simple bool API.
PHP
Raw
<?php
function safeJsonDecode(string $json, bool $assoc = true, int $depth = 64): array|object|null|false {
    if ($json === '') return false;
    try {
        return json_decode($json, $assoc, $depth, JSON_THROW_ON_ERROR);
    } catch (JsonException $e) {
        error_log('JSON decode failed: ' . $e->getMessage());
        return false;
    }
}

$data = safeJsonDecode('{"ok": true}');     // ['ok' => true]
$bad  = safeJsonDecode('{not json}');       // false
if ($bad === false) { /* handle parse error */ }
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.