开发者

json_encode remove quotes from keys?

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

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

The开发者_如何学C 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?


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.


If you want to convert your JSON to print a javascript object (that was my case) you can use ugly regex like this:

$myJsonString = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', $myJsonString);

Source: https://hdtuto.com/article/php-how-to-remove-double-quotes-from-json-array-keys


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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜