如何使用jquery从json中提取特定字段

时间:2012-06-11 06:09:57

标签: jquery

我正在使用jquery创建一个自动完成组件,其中建议来自Solr的一个字段。我无法从相应的json格式中提取值。 json文件是给定的,我需要提取Query字段的值。

{
    "responseHeader": {
        "status": 0,
        "QTime": 0,
        "params": {
            "q": "Query:cr*\r\n",
            "wt": "json"
        }
    },
    "response": {
        "numFound": 16,
        "start": 0,
        "docs": [{
            "id": "90268125-f806-428c-889b-696172c55356",
            "Query": "cricket",
            "Hits": 66,
            "RespTime": 359},
        {
            "id": "d5871725-0d4f-42bc-8180-9328ed81c644",
            "Query": "cricketmania",
            "Hits": 66,
            "RespTime": 156}]
    }
}

1 个答案:

答案 0 :(得分:1)

var data = {
    "responseHeader": {
        "status": 0,
        "QTime": 0,
        "params": {
            "q": "Query:cr*\r\n",
            "wt": "json"
        }
    },
    "response": {
        "numFound": 16,
        "start": 0,
        "docs": [{
            "id": "90268125-f806-428c-889b-696172c55356",
            "Query": "cricket",
            "Hits": 66,
            "RespTime": 359},
        {
            "id": "d5871725-0d4f-42bc-8180-9328ed81c644",
            "Query": "cricketmania",
            "Hits": 66,
            "RespTime": 156}]
    }
}

data.response.docs[0].Query

data.response.docs[1].Query

<强> DEMO

使用循环:

$.each(data.response.docs, function(i, val) {
  console.log(val.Query);
});

<强> DEMO

您也可以使用简单的for循环:

for( var key in data.response.docs ) {
   alert(data.response.docs[key].Query);
};

<强> DEMO