如何使用python访问json对象中的元素?

at0kjp5o  于 2021-06-14  发布在  ElasticSearch
关注(0)|答案(1)|浏览(405)

我有一个从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

访问此元素的正确方法是什么?谢谢您!

5lhxktic

5lhxktic1#

这里缺少一个变量名。例如,如果:

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"])

相关问题