Detecting json_decode() failure in PHP

json, php

Solution

You would have to check `json_last_error` for any JSON parsing errors.

json_decode($string);
switch(json_last_error()) {
    case JSON_ERROR_DEPTH:
        echo ' - Maximum stack depth exceeded';
    break;
    case JSON_ERROR_CTRL_CHAR:
        echo ' - Unexpected control character found';
    break;
    case JSON_ERROR_SYNTAX:
        echo ' - Syntax error, malformed JSON';
    break;
    case JSON_ERROR_NONE:
        echo ' - No errors';
    break;
}

Problem

When using PHP's `json_decode()`, I don't see a way to distinguish between a `NULL` return value indicating a failure in decoding and a correctly decoded `NULL` value: ``` var_dump(json_decode('nonsense')); // returns NULL var_dump(json_decode(json_encode(NULL))); // also returns NULL ``` And case one doesn't throw an exception. So I'm not sure how to test for a decode failure. Ideas?

Original source