简体   繁体   中英

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.

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:

""
" chars "

In other words, double quotes (not single) are necessary for JSON strings. How are you getting this 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

A value can be a string in double quotes , or [...]

The first string isn't valid JSON. That's why json_decode() returns NULL . You can verify this using an online validator such as jsonlint.com .

According to the specification in json.org (emphasis mine):

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. Use native encoding functions like json_encode() instead of hand-crafting it (if you're doing that). That way, you can be sure that the resultant JSON string is valid.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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