2012-06-11 66 views
0

我正在使用jquery創建一個自動完成組件,其中的建議來自Solr.I的一個字段,我無法從相應的json格式中提取值。 json文件是給定的,我需要提取查詢字段的值。如何使用jquery從json中提取特定字段

{ 
    "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
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

+0

我想這和它的顯示我「未定義」當我試圖打印在一個警告框。 – user1438978

+0

@ user1438978你試過了哪一個? – thecodeparadox

+0

alert(data.response.docs [0] .Query);給我一個警告框中的[Object Object]! – user1438978

相關問題