/**
 * Wrapper for json_decode that throws when an error occurs.
 *
 * @param string $json    JSON data to parse
 * @param bool $assoc     When true, returned objects will be converted
 *                        into associative arrays.
 * @param int    $depth   User specified recursion depth.
 * @param int    $options Bitmask of JSON decode options.
 *
 * @return mixed
 * @throws Exception\InvalidArgumentException if the JSON cannot be decoded.
 * @link http://www.php.net/manual/en/function.json-decode.php
 */
function json_decode($json, $assoc = false, $depth = 512, $options = 0)
{
    $data = \json_decode($json, $assoc, $depth, $options);
    if (JSON_ERROR_NONE !== json_last_error()) {
        throw new Exception\InvalidArgumentException(
            'json_decode error: ' . json_last_error_msg()
        );
    }

    return $data;
}

/**
 * Wrapper for JSON encoding that throws when an error occurs.
 *
 * @param mixed $value   The value being encoded
 * @param int    $options JSON encode option bitmask
 * @param int    $depth   Set the maximum depth. Must be greater than zero.
 *
 * @return string
 * @throws Exception\InvalidArgumentException if the JSON cannot be encoded.
 * @link http://www.php.net/manual/en/function.json-encode.php
 */
function json_encode($value, $options = 0, $depth = 512)
{
    $json = \json_encode($value, $options, $depth);
    if (JSON_ERROR_NONE !== json_last_error()) {
        throw new Exception\InvalidArgumentException(
            'json_encode error: ' . json_last_error_msg()
        );
    }

    return $json;
}

json_last_error() int 返回最后发生的错误

JSON 错误码

常量 含义 可用性
JSON_ERROR_NONE 没有错误发生
JSON_ERROR_DEPTH 到达了最大堆栈深度
JSON_ERROR_STATE_MISMATCH 无效或异常的 JSON
JSON_ERROR_CTRL_CHAR 控制字符错误,可能是编码不对
JSON_ERROR_SYNTAX 语法错误
JSON_ERROR_UTF8 异常的 UTF-8 字符,也许是因为不正确的编码。 PHP 5.3.3
JSON_ERROR_RECURSION One or more recursive references in the value to be encoded PHP 5.5.0
JSON_ERROR_INF_OR_NAN One or more NAN or INF values in the value to be encoded PHP 5.5.0
JSON_ERROR_UNSUPPORTED_TYPE 指定的类型,值无法编码。 PHP 5.5.0
JSON_ERROR_INVALID_PROPERTY_NAME 指定的属性名无法编码。 PHP 7.0.0
JSON_ERROR_UTF16 畸形的 UTF-16 字符,可能因为字符编码不正确。 PHP 7.0.0

案例:判断字符串是否是json格式 ```` public function isJson():bool { //判断长度 if (!$this->length()) { return false; }

			//json解码
    json_decode($this->str);
			
			//判断解码是否发生错误
    return (json_last_error() === JSON_ERROR_NONE);
}
	````