How to Validate JSON in PHP

Posted on November 7, 2018 at 10:49 pm

Simple PHP function to validate JSON in PHP:

function is_valid_json($string) {
    return !empty($string) && is_string($string) && is_array(json_decode($string, true)) && json_last_error() === 0;
}

Alternatively you can do like this (doing only one json_decode() call):

$output = json_decode($string, true);
 
if (!is_array($output) || json_last_error() !== 0)
{
    echo "Failed to decode JSON!";
    exit;
}

Here is another example showing the JSON error message:

$result = json_decode($string);
 
switch (json_last_error()) {
    case JSON_ERROR_NONE:
        $error = ''; // JSON is valid // No error has occurred
        break;
    case JSON_ERROR_DEPTH:
        $error = 'The maximum stack depth has been exceeded.';
        break;
    case JSON_ERROR_STATE_MISMATCH:
        $error = 'Invalid or malformed JSON.';
        break;
    case JSON_ERROR_CTRL_CHAR:
        $error = 'Control character error, possibly incorrectly encoded.';
        break;
    case JSON_ERROR_SYNTAX:
        $error = 'Syntax error, malformed JSON.';
        break;
    // PHP >= 5.3.3
    case JSON_ERROR_UTF8:
        $error = 'Malformed UTF-8 characters, possibly incorrectly encoded.';
        break;
    // PHP >= 5.5.0
    case JSON_ERROR_RECURSION:
        $error = 'One or more recursive references in the value to be encoded.';
        break;
    // PHP >= 5.5.0
    case JSON_ERROR_INF_OR_NAN:
        $error = 'One or more NAN or INF values in the value to be encoded.';
        break;
    case JSON_ERROR_UNSUPPORTED_TYPE:
        $error = 'A value of a type that cannot be encoded was given.';
        break;
    default:
        $error = 'Unknown JSON error occured.';
        break;
}
 
if ($error !== '') 
{
    echo "Failed to decode JSON: ".$error;
    exit;
}

Reference:

https://stackoverflow.com/a/15198925

Receive updates via email

Other Posts

Updated Posts