前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >json_decode在php中的一些无法解析的字符串

json_decode在php中的一些无法解析的字符串

作者头像
蛋未明
发布2018-06-07 15:36:59
4K0
发布2018-06-07 15:36:59
举报
文章被收录于专栏:蛋未明的专栏

 关于json_decode在php中的一些无法解析的字符串,包括以下几种常见类型。

一、Bug #42186 json_decode() won't work with \l

当字符串中含有\l的时候,json_decode是无法解析,测试代码:

代码语言:javascript
复制
echo "***********json_decode() won't work with \l*************<br/>";
$json = '{"stringwithbreak":"line with a \lbreak!"}';
var_dump($json);//stringwithbreak":"line with a \lbreak!
var_dump(json_decode($json, true));//null

解决办法:

主要是将\l进行替换,当然如果真的需要‘\l’,我们就必须不使用json_decode进行解析,可以当作当个字符进行提交。

代码语言:javascript
复制
var_dump(str_replace("\\l", "", $json));//stringwithbreak":"line with a break!
print_r(json_decode(str_replace("\\l", "", $json), true));//Array ( [stringwithbreak] => line with a break! ) 

二、Tabs in Javascript strings break json_decode()

当字符串中含有tab键时,json_decode()无法解析,例如代码3-1

代码语言:javascript
复制
echo "<br/>***********Tabs in Javascript strings break json_decode()*************<br/>";
var_dump(json_decode('{ "abc": 12, "foo": "bar	bar" }'));

执行后的返回结果为null

解决办法:

1、当遇到含有tab键输入的字符串时,我们应该避免使用json将数据传到php,然后使用php作为解析。

2、同样可以使用如下3-2代码方式进行替换

代码语言:javascript
复制
$myStr = '{ "abc": 12, "foo": "bar	bar" }';
$replaceStr = str_replace("	", "\\t", $myStr);
var_dump($replaceStr);
var_dump(json_decode($replaceStr ));

三、json_decode returns false when leading zeros aren't escaped with double quotes

当json的value值为number类型,而且该number以0开头,例如代码4-1

代码语言:javascript
复制
echo "<br/>***********json_decode returns false when leading zeros aren't escaped with double quotes*************<br/>";
$noZeroNumber = '{
  "test" : 6
}';
$zeroNumber= '{
  "test" : 06
}';
var_dump(json_decode($noZeroNumber));//object(stdClass)[1]
  public 'test' => int 6
var_dump(json_decode($zeroNumber));//null

或许对于这种问题很少出现,但是一旦出现了,我们就很难去查找问题的原因。

四、decode chokes on unquoted object keys

当key值没有使用引号时,会无法解析,例如代码5-1

代码语言:javascript
复制
echo "<br/>***********decode chokes on unquoted object keys*************<br/>";
var_dump(json_decode('{"a":"tan","model":"sedan"}'));//object(stdClass)[1]
  public 'a' => string 'tan' (length=3)
  public 'model' => string 'sedan' (length=5)
var_dump(json_decode('{a:"tan","model":"sedan"}'));//null
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2012年08月09日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档