Json_encode remove quotes from keys?

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

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

Return:

 {'foo' : 'bar'} 

The key is passed as a literal, and this disables my script. I really need:

 { foo : 'bar' } 

Does json_encode do this or do I need to strip the quotes from some ugly regex?

+6
json php
source share
4 answers

When I test this piece of code:

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

I get:

 {"foo":"bar"} 

What is valid JSON.

(Note that these are double quotes, not the simple quotes you sent)


You are asking:

 { foo : 'bar' } 

valid Javascript but invalid JSON - so json_encode will not return this.

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


Instead of “stripping yourself of quotes with some ugly regular expression”, you should adapt your code, so it accepts valid JSON: this is, in my opinion, better.

+14
source share

No, json_encode will not do this for you. The json specification explicitly requires the keys to be quotation marks. This is to ensure that keys that are javascript reserved words do not violate the data object.

+2
source share

How to disable your script?

And beyond the JSON specification , key names must be strings. The second snippet you posted is invalid JSON.

0
source share

Thanks, everyone. I did not know this about the JSON specification. The problem was actually with my script because I did not set my $ .ajax () data type for the "json" function

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

0
source share

All Articles