JSON数据的一部分被解释为对象,而类似的部分则被解释为数组:为什么
One part of JSON data being interpreted as an object and an similar part being interpreted as an array: why?
我有一个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": {}}'
相关文章:
- 请解释为什么“改变数字的值甚至没有意义”
- '其他'在我的if/else语句中,从来没有发生过——有人能解释为什么吗
- 解释为什么 '+[] == 0' 在 Javascript 中输出 'true'
- 请解释为什么JSON.stringify输出与这个简短示例中的toString输出不同
- 谁能解释为什么我的日期函数通过 JS 日期对象给了我错误的转换
- 有人可以解释为什么这个测试表明jquery $.each比本机更快
- ibooks中的event.preventDefault():谁能解释为什么这不起作用
- 有人可以向我解释为什么我对此出现堆栈溢出
- 有人能解释为什么JS正则表达式在这种情况下失败吗
- 解释为什么这个年龄没有改变全球可变年龄
- 有人可以解释为什么这个 javascript 代码会提醒这些(item3 undefined,item3 undefin
- 解释为什么for循环在JavaScript中会这样
- 请解释为什么以及如何+new Date();作为'变通方法'用于IE8或更低版本中的Date.now()
- 是否存在“;编程文化;解释为什么FF从measureText方法返回长分数
- 有人能解释为什么FOR和WHILE循环在Javascript中有不同的输出
- WebGL代码的解释-为什么它是这样工作的
- 谁能解释为什么我得到这个错误在Javascript?[无法读取属性'length'未定义)
- 我的JSON有什么问题?解析并解释为什么代码没有按照出现的顺序执行
- 有人可以解释为什么runAnimation()是不可访问的,当从点击处理程序$('#sm_logo')调
- 有人能解释为什么这个jQuery.offset()每次使用时都会移位吗?