Reputation:
This is the code:
$json = "{ a: 'hello', b: 'world' }";
var_dump($json);
var_dump(json_decode($json));
The first outputs:
{ a: 'hello', b: 'world' }
The second outputs nothing. I want the second to output something like:
array(
'a' => 'hello',
'b' => 'world'
)
How to do this? Is my JSON format wrong?
Upvotes: 1
Views: 213
Reputation: 14302
Properly formatted JSON requires keys and string values to be enclosed in double-quotes. Change it to this:
$json = '{ "a": "hello", "b": "world" }';
var_dump($json);
var_dump(json_decode($json));
Upvotes: 8
Reputation: 4808
Because that is not valid JSON. The following is the appropriate form:
{"a":"hello","b":"world"}
Upvotes: 3
Reputation: 19040
Keys in JSON must be "-quoted :
{"a": "hello", "b": "world"}
also, you can use php's json_last_error()
when you need to know what went wrong :).
Upvotes: 21
Reputation: 382150
This is no proper JSON. You need to have quotes around property names and string values.
Try
$json = '{ "a": "hello", "b": "world" }';
Upvotes: 4