views:

342

answers:

4

If I use json_encode() on an array like this:

return json_encode(array( 'foo' => 'bar'));

The return is:

{'foo' : 'bar'}

The key is passed as a literal, and that is tripping up my script. What I really need is:

{ foo : 'bar' }

Does json_encode do that or do I have to strip the quotes out myself with some ugly regex?

+7  A: 

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.

Pascal MARTIN
A: 

How is it tripping up your script?

And per the JSON specification, key names are supposed to be strings. The 2nd snippet you posted is not valid JSON.

Peter Bailey
+1  A: 

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.

Alan Storm
A: 

Thanks, everyone. I did not know that about the JSON spec. The issue was in fact with my script because I had not set the datatype of my $.ajax() function to "json"

What I learned today -- JSON and Javascript are not the same thing!

Aaron