我有一个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'和'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字符串中。
答案 0 :(得分:1)
employjobs
可能是空的。如果它永远不应该是空的,你需要研究它。如果它是空的有效,php默认会省略JSON的空数组语法。如果这是不合需要的(即您想要一个空对象),可以使用JSON_FORCE_OBJECT
的{{1}}选项:
json_encode
这将被省略为
echo json_encode($data, JSON_FORCE_OBJECT);