PHP json_encode问题

Ste*_*ven 0 javascript php json parse-platform

我有一堆值和PHP数组,我需要将其转换为JSON值,以便通过CURL发布到parse.com

问题是PHP数组被转换为JSON对象(字符串作为键和值,vs字符串作为值)

我结束了

{"showtime":{"Parkne":"1348109940"}}
Run Code Online (Sandbox Code Playgroud)

而不是

{"showtime":{Parkne:"1348109940"}}
Run Code Online (Sandbox Code Playgroud)

并解析抱怨这是一个对象而不是数组,因此不接受它.

{"showtime":{"Parkne":"1348109940"}}
Run Code Online (Sandbox Code Playgroud)

是一个JSON对象(key = a string)

无论如何使用json_encode?或一些解决方案?

Mar*_*c B 6

这是JSON规范:必须引用对象键.虽然您的第一个未加引号的版本是有效的Javascript,所以是引用的版本,并且两者都将在任何Javascript引擎中进行相同的解析.但在JSON中,必须引用键.http://json.org


跟进:

展示你如何定义你的数组,除非上面的样本是你的数组.这一切都取决于你如何定义你正在编码的PHP结构.

// plain array with implicit numeric keying
php > $arr = array('hello', 'there');
php > echo json_encode($arr);
["hello","there"]   <--- array

// array with string keys, aka 'object' in json/javascript
php > $arr2 = array('hello' => 'there');
php > echo json_encode($arr2);
{"hello":"there"} <-- object

// array with explicit numeric keying
php > $arr3 = array(0 => 'hello', 1 => 'there');
php > echo json_encode($arr3);
["hello","there"]  <-- array

// array with mixed implicit/explicit numeric keying
php > $arr4 = array('hello', 1 => 'there');
php > echo json_encode($arr4);
["hello","there"] <-- array

// array with mixed numeric/string keying
php > $arr5 = array('hello' => 'there', 1 => 'foo');
php > echo json_encode($arr5);
{"hello":"there","1":"foo"}   <--object
Run Code Online (Sandbox Code Playgroud)