簡體   English   中英

如何使用 python 從特定鍵中獲取值?

[英]How to get the value from particular key using python?

resp = {
  "Name": "test",
  "os": "windows",
  "Agent": {
    "id": "2",
    "status": [
      {
        "code": "123",
        "level": "Info",
        "displayStatus": "Ready",
        "message": "running",
        "time": "2022-01-18T09:51:08+00:00"
      }
    ]
}

我正在嘗試從 JSON 獲取時間值。 我嘗試了下面的代碼,但遇到了 dict 錯誤

resp1 = json.loads(resp)
resp2 = resp1.values()
creation_time = resp2.get("Agent").get("status")
val= creation_time["time"]
print(val) ## Thrwoing error as dict_values has no 'get'

關於 python 如何獲取這個時間值的任何建議

我注意到的幾個問題

  1. 您正在嘗試使用 json 的負載 function 加載 Dict 類型,這應該得到 json 格式的字符串(例如: '{ "name":"John", "age":30, "city":"New York"}' )

  2. 您嘗試在聲明之前訪問 resp2(我猜您的意思是“resp1?”)

  3. 您正在使用沒有聲明的 resp3。

  4. 你不見了}

  5. 您不需要 the.value() function 因為它會返回一個列表。

  6. 此外,創建時間是一個包含一個 object 的列表,因此您也需要訪問它。

考慮到這一切,您可以按如下方式進行更改:

import json
resp = '{ "Name": "test", "os": "windows","Agent": {"id": "2","status": [{"code": "123","level": "Info","displayStatus": "Ready","message": "running","time": "2022-01-18T09:51:08+00:00"}]}}'

resp1 = json.loads(resp)
creation_time = resp1.get("Agent").get("status")
val= creation_time[0]["time"]
print(val) 

您只需要使用[]訪問字典,如下所示:

resp = {"Name": "test", "os": "windows", "Agent": {"id": "2","status": [{"code": "123","level": "Info","displayStatus": "Ready","message": "running","time": "2022-01-18T09:51:08+00:00"}]}}
creation_time = resp["Agent"]["status"]
val= creation_time[0]["time"]
print(val)

Output:

2022-01-18T09:51:08+00:00

暫無
暫無

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

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