简体   繁体   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"
      }
    ]
}

I am trying to get the time value from the JSON.我正在尝试从 JSON 获取时间值。 I tried the below code but faced error with dict我尝试了下面的代码,但遇到了 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'

Any suggestion on python how to take this time values关于 python 如何获取这个时间值的任何建议

Few problems I noticed我注意到的几个问题

  1. You are trying to load a Dict type using the json's loads function which is supposed to get a string in json format (ex: '{ "name":"John", "age":30, "city":"New York"}' )您正在尝试使用 json 的负载 function 加载 Dict 类型,这应该得到 json 格式的字符串(例如: '{ "name":"John", "age":30, "city":"New York"}' )

  2. You tried to access resp2 before declaration (I guessed you meant "resp1?")您尝试在声明之前访问 resp2(我猜您的意思是“resp1?”)

  3. You're using resp3 without declaration.您正在使用没有声明的 resp3。

  4. You are missing }你不见了}

  5. You don't need the.value() function because it will return a list.您不需要 the.value() function 因为它会返回一个列表。

  6. Also creation time is a list with one object, so you need to access it too.此外,创建时间是一个包含一个 object 的列表,因此您也需要访问它。

Considering all this, you can change it as follows:考虑到这一切,您可以按如下方式进行更改:

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) 

You just need to access the dicts using [] like so:您只需要使用[]访问字典,如下所示:

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: Output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM