anniu1122

json_decode

版本限制 :(PHP 5 >= 5.2.0, PECL json >= 1.2.0, PHP 7)

描        述: json_decode — 对 JSON 格式的字符串进行解码 接受一个 JSON 编码的字符串并且把它转换为 PHP 变量

使        用( mixed ) json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
 
json相关处理对json文本串的格式要求非常严格,很可能使用该函数得到的返回值是NULL
可以使用使用json_last_error()函数获取到的返回值来帮助我们判断出问题的原因。
json_last_error错误msg对照表:
  • 0 = JSON_ERROR_NONE
  • 1 = JSON_ERROR_DEPTH
  • 2 = JSON_ERROR_STATE_MISMATCH
  • 3 = JSON_ERROR_CTRL_CHAR
  • 4 = JSON_ERROR_SYNTAX
  • 5 = JSON_ERROR_UTF8
其中如果提示错误JSON_ERROR_SYNTAX(Syntax error),表示json串格式错误。
 
排错方式:
1. 格式: json字符串必须用双引号包含
$output = str_replace("\'",  \'"\',  $output);
2. 编码: json字符串必须是utf8编码
$output = iconv(\'gbk\',  \'utf8\',  $output);
3. 符号: 不能有多余的逗号 如:[1,2,]
用正则替换掉,preg_replace(\'/,s*([]}])/m\', \'$1\', $output)
 
示例:
$json = "{\'item_list\':[{\'item_id\':556553427228,\'item_show_name\':\' \'},{\'item_id\':556553371311,\'item_show_name\':\' \'},{\'item_id\':556553387348,\'item_show_name\':\' \'}]}";
$json = str_replace("\'", \'"\', $json);//如果不加这行代码会报错 错误是4 语法错误 排错得知是符号应该用双引号包含每项
$res = json_decode($json, true);
var_export($res);
echo json_last_error();die;

 

分类:

技术点:

相关文章: