0

我有一个输出text/json以下输出的 php 脚本:

{"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 字符串中。

4

1 回答 1

1

employjobs在某些情况下可能是空的。如果它永远不应该是空的,你需要调查一下。如果它为空有效,php 默认会省略 JSON 的空数组语法。如果这是不可取的(即您想要一个空对象),您可以使用以下JSON_FORCE_OBJECT选项json_encode

echo json_encode($data, JSON_FORCE_OBJECT);

这将被省略为

'{"labels": "object with various values", "employjobs": {}}'
于 2013-07-10T11:24:13.947 回答