我有一个php脚本,它输出text/json
,输出如下:
{"labels":{"ftemp":"Full time employment only","ptemp":"Part time employment only","study":"Further study only","workstudy":"Work and Study","noavail":"Not available for work","noemp":"Unemployed","other":"Other","refusal":"Information Refused"},"employjobs":{"Cambridge Beds Co Ltd.":"Accounts Assistant","Chinese Company":"Accountant"}}
格式更漂亮,看起来像这样:
{
"labels":
{
"ftemp":"Full time employment only",
"ptemp":"Part time employment only",
"study":"Further study only",
"workstudy":"Work and Study",
"noavail":"Not available for work",
"noemp":"Unemployed",
"other":"Other",
"refusal":"Information Refused"
},
"employjobs":
{
"Cambridge Beds Co Ltd.":"Accounts Assistant",
"Chinese Company":"Accountant"
}
}
现在,对我来说,"labels"answers"employjobs"看起来都是具有键值对的json对象。但是,当我对脚本进行JQuery getJSON调用时,在返回的数据对象中,"labels"是一个对象,但"employjobs"是空数组。
我错过了什么?json字符串的两个位的格式看起来是一样的,那么为什么一个被解释为对象,另一个被理解为空数组呢?
非常感谢收到任何帮助,提前谢谢。
更新:以下是在PHP脚本中的数据通过json_encode函数之前的print_r的输出:
Array
(
[labels] => Array
(
[ftemp] => Full time employment only
[ptemp] => Part time employment only
[study] => Further study only
[workstudy] => Work and Study
[noavail] => Not available for work
[noemp] => Unemployed
[other] => Other
[refusal] => Information Refused
)
[employjobs] => Array
(
[Cambridge Beds Co Ltd.] => Accounts Assistant
[Chinese Company] => Accountant
)
)
正如您所看到的,'labels'和'employjobs'都是键值对数组,这反映在PHP脚本输出的JSON字符串中。
employjobs
在某些情况下可能为空。如果它永远都不应该是空的,你需要调查一下。如果它为空是有效的,php将默认省略JSON的空数组语法。如果这是不可取的(即您想要一个空对象),您可以使用json_encode
:的JSON_FORCE_OBJECT
选项
echo json_encode($data, JSON_FORCE_OBJECT);
这将被省略为
'{"labels": "object with various values", "employjobs": {}}'