Parse JSON Safely

Parse JSON with a fallback value returned if parsing fails.

Code

Utilities
$result = json_decode($jsonStr);
json_encode($result !== null ? $result : json_decode($fallback));

Parameters

JSON string to parse.

Fallback value if parsing fails (as JSON).

Server

More PHP Snippets