user967451
user967451

Reputation:

Why isn't json_decode() function working?

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

Answers (4)

svidgen
svidgen

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

Justin Bicknell
Justin Bicknell

Reputation: 4808

Because that is not valid JSON. The following is the appropriate form:

{"a":"hello","b":"world"}

Upvotes: 3

Ven
Ven

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

Denys Séguret
Denys Séguret

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

Related Questions