代码之家  ›  专栏  ›  技术社区  ›  user213154

在PHP中检测json_decode()失败

  •  18
  • user213154  · 技术社区  · 16 年前

    使用PHP时 json_decode() 我看不出区分 NULL 返回值,指示解码失败和正确解码 无效的 值:

    var_dump(json_decode('nonsense')); // returns NULL
    var_dump(json_decode(json_encode(NULL))); // also returns NULL
    

    第一种情况不会引发异常。所以我不知道如何测试解码失败。

    思想?

    1 回复  |  直到 16 年前
        1
  •  33
  •   Anthony Forloney    16 年前

    你得检查一下 json_last_error 对于任何JSON解析错误。

    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;
    }