views:

153

answers:

1

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?

+6  A: 

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;
}
Anthony Forloney
This being new in php 5.3 would explain why i didn't know about it. Thanks for pointing it out. I'll download fresh documentation today.
fsb
Not a problem, glad I could help.
Anthony Forloney