簡體   English   中英

如何使用 Python 訪問 json 對象中的元素?

[英]how can I access an element within a json object with Python?

我有一個從 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

訪問此元素的正確方法是什么? 謝謝!

你在這里缺少一個變量名。 例如,如果:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM