我有一个从Elasticsearch查询返回的json对象,如下所示:
{"took": 10, "timed_out": false, "_shards": {"total": 5, "successful": 5, "skipped": 0, "failed": 0}, "hits": {"total": 1, "max_score": 0.5753642, "hits": [{"_index": "match", "_type": "score", "_id": "J_J1zGcBjpp4O0gQqUq_", "_score": 0.5753642, "_source": {"tournament_id": 1, "board_number": "2", "nsp": "1", "ewp": "8", "contract": "3C", "by": "N", "tricks": "9", "nsscore": "110", "ewscore": "0", "timestamp": "2018-12-20T16:32:02.440315"}}]}}
我需要访问“ nsscore”元素。当我尝试以下操作时:
print(["hits"]["hits"]["_source"]["nsscore"])
我收到以下错误:
print(["hits"]["hits"]["_source"]["nsscore"])
TypeError: list indices must be integers or slices, not str
什么是访问此元素的正确方法?谢谢!
答案 0 :(得分:1)
您在这里缺少变量名。 例如,如果:
variable = {"took": 10, "timed_out": false, "_shards": {"total": 5, "successful": 5, "skipped": 0, "failed": 0}, "hits": {"total": 1, "max_score": 0.5753642, "hits": [{"_index": "match", "_type": "score", "_id": "J_J1zGcBjpp4O0gQqUq_", "_score": 0.5753642, "_source": {"tournament_id": 1, "board_number": "2", "nsp": "1", "ewp": "8", "contract": "3C", "by": "N", "tricks": "9", "nsscore": "110", "ewscore": "0", "timestamp": "2018-12-20T16:32:02.440315"}}]}}
然后:
print(variable["hits"]["hits"][0]["_source"]["nsscore"])