json_encode remove quotes from keys?

When I test this portion of code :

echo json_encode(array( 'foo' => 'bar'));
die;

I get :

{"foo":"bar"}

Which is valid JSON.

(Note these are double-quotes, and not simple-quotes as you posted)


The ouput you are asking for :

{ foo : 'bar' }

is valid Javascript, but is not valid JSON -- so json_encode will not return that.

See json.org for the specification of the JSON format -- which is a subset of Javascript, and not Javascript itself.


Instead of "stripping the quotes out myself with some ugly regex", you should adapt your code, so it accepts valid JSON : this is way better, in my opinion.


No, json_encode will not do this for you. The json specification specifcally requires that keys be quoted strings. This is done to ensure that keys which are javascript reserved words won't break the data object.

Tags:

Php

Json