我的代码如下:使用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