简体   繁体   English

PHP 的 json_decode 有单引号但不是双引号的问题

[英]PHP's json_decode having problems with single but not double quotes

Easiest to explain via example:通过示例最容易解释:

var_dump(json_decode("[{'a':'b'},{'c':'d'},{'e':'f'}]")); // NULL
var_dump(json_decode('[{"a":"b"},{"c":"d"},{"e":"f"}]')); // array(3) { [0]=> object(stdClass)#1 (1) { ["a"]=> string(1) "b" } [1]=> object(stdClass)#2 (1) { ["c"]=> string(1) "d" } [2]=> object(stdClass)#3 (1) { ["e"]=> string(1) "f" } }

As you can see the first example where single quotes are used returns NULL meaning an error while the second one works fine.正如您所看到的,第一个使用单引号的示例返回 NULL 表示错误,而第二个工作正常。

Any idea as to why it is doing it or what I can do to help prevent problems other than doing a bunch of string manipulation?知道为什么要这样做,或者除了做一堆字符串操作之外,我还能做些什么来帮助防止出现问题?

A string in JSON is defined as: JSON 中的字符串定义为:

""
" chars "

In other words, double quotes (not single) are necessary for JSON strings.换句话说,JSON 字符串需要双引号(不是单引号)。 How are you getting this JSON?你是如何得到这个 JSON 的? We can look at a possible solution for validating/fixing the string before decoding.我们可以看看在解码之前验证/修复字符串的可能解决方案。

Source: http://www.json.org/ and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf来源: http : //www.json.org/http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf

A value can be a string in double quotes , or [...]值可以是双引号中的字符串,或 [...]

The first string isn't valid JSON.第一个字符串不是有效的 JSON。 That's why json_decode() returns NULL .这就是json_decode()返回NULL的原因。 You can verify this using an online validator such as jsonlint.com .您可以使用在线验证器(例如jsonlint.com )进行验证。

According to the specification in json.org (emphasis mine):根据json.org 中规范(重点是我的):

A value can be a string in double quotes , or a number, or true or false or null, or an object or an array.值可以是双引号中的字符串、数字、真假或空值、对象或数组。 These structures can be nested.这些结构可以嵌套。

Fix your JSON.修复您的 JSON。 Use native encoding functions like json_encode() instead of hand-crafting it (if you're doing that).使用像json_encode()这样的原生编码函数而不是手工制作它(如果你这样做的话)。 That way, you can be sure that the resultant JSON string is valid.这样,您就可以确定生成的 JSON 字符串是有效的。

$siteParameters = str_replace('\'','"',$siteParameters);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM