我的代碼如下:使用Python和elasticsearch,我如何循環返回的JSON對象?
import json
from elasticsearch import Elasticsearch
es = Elasticsearch()
resp = es.search(index="mynewcontacts", body={"query": {"match_all": {}}})
response = json.dumps(resp)
data = json.loads(response)
#print data["hits"]["hits"][0]["_source"]["email"]
for row in data:
print row["hits"]["hits"][0]["_source"]["email"]
return "OK"
產生這種截斷(爲方便起見)JSON:當我試圖
{"timed_out": false, "took": 1, "_shards": {"successful": 5, "total": 5, "failed": 0}, "hits": {"max_score": 1.0, "total": 7, "hits": [{"_index": "mynewcontacts", "_type": "contact", "_score": 1.0,
"_source": {"email": "[email protected]", "position": "Sr.Researcher", "last": "Zhuo", "first": "Sharon", "company": "Tabridge Executive Search"}, "_id": "AVYmLMlKJVSAh7zyC0xf"},
{"_index": "mynewcontacts", "_type": "contact", "_score": 1.0, "_source": {"email": "[email protected]", "position": "Vice President", "last": "Springthorpe", "first": "Andrew", "company": "SBC Group"}, "_id": "AVYmLMlRJVSAh7zyC0xg"}, {"_index": "mynewcontacts", "_type": "contact", "_score": 1.0, "_source": {"email": "[email protected]", "position": "Financial Advisor", "last": "Bell", "first": "Margaret Jacqueline", "company": "Streamline"}, "_id": "AVYmLMlXJVSAh7zyC0xh"}, {"_index": "mynewcontacts", "_type": "contact", "_score": 1.0, "_source": {"email": "[email protected]", "position": "Technical Solutions Manager MMS North Asia", "last": "Okai", "first": "Kensuke", "company": "Criteo"}, "_id": "AVYmLMlfJVSAh7zyC0xi"}, {"_index": "mynewcontacts", "_type": "contact", "_score": 1.0, "_source": {"email": "[email protected]", "position": "Sr. Strategic Account Executive", "last": "Kato", "first": "Mizuto", "company": "Twitter"}, "_id": "AVYmLMlkJVSAh7zyC0xj"}, {"_index": "mynewcontacts", "_type": "contact", "_score": 1.0, "_source": {"email": "[email protected]", "position": "Design Manager", "last": "Okada", "first": "Kengo", "company": "ON Semiconductor"}, "_id": "AVYmLMlpJVSAh7zyC0xk"}, {"_index": "mynewcontacts", "_type": "contact", "_score": 1.0, "_source": {"email": "[email protected]", "position": "Legal Counsel", "last": "Lei", "first": "Yangzi (Karen)", "company": "Samsung China Semiconductor"}, "_id": "AVYmLMkUJVSAh7zyC0xe"}]}}
:
print data["hits"]["hits"][0]["_source"]["email"]
它打印的第一封電子郵件罰款當我嘗試循環與
for row in data:
print row["hits"]["hits"][0]["_source"]["email"]
我收到一個錯誤:
TypeError: string indices must be integers
請可有人建議如何我可以通過正確的項目重複?非常感謝!
謝謝你,完美的作品。但爲什麼? – user1903663
在你原來的代碼中,你已經檢索了一個字典鍵太深的JSON數據。 – drsnark