如何在jquery中的json中检查数组是否存在

时间:2013-07-08 11:22:41

标签: javascript jquery

我有以下JSON作为回复:

{
    "responseHeader": {
        "status": 0,
        "QTime": 1
    },
    "spellcheck": {
        "suggestions": [
            "goo",
            {
                "numFound": 4,
                "startOffset": 0,
                "endOffset": 3,
                "suggestion": [
                    "good",
                    "google",
                    "google's",
                    "goodbye"
                ]
            },
            "collation",
            "good"
        ]
    }
}

现在基于查询,我有时会得到这个JSON:

{
    "responseHeader": {
        "status": 0,
        "QTime": 1
    }
}

我想在'spellcheck'不存在时检查我的jQuery代码。因为否则会引发异常并且脚本会停止执行。

我试过这个:

if(typeof(response.spellcheck)!=='undefined')

但它会抛出异常。

帮助。

4 个答案:

答案 0 :(得分:1)

你可以说if(response && response.spellcheck) ...

答案 1 :(得分:1)

尝试hasOwnProperty

if(response.hasOwnProperty("spellcheck")) {
    ...
}

答案 2 :(得分:0)

尝试if (response && response.hasOwnProperty('spellcheck') && response.spellcheck) {/*your code here*/}

答案 3 :(得分:-1)

将你的json分配给变量说响应并检查它的长度

if ( response['spellcheck'].length < 1 ) {
// it's empty
}
相关问题