繁体   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