Reputation: 26993
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?
Upvotes: 2
Views: 3696
Reputation: 20486
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 [...]
Upvotes: 5
Reputation: 76666
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.
Upvotes: 1