【问题标题】:How to decode this type of json in Python using json library? [closed]如何使用 json 库在 Python 中解码这种类型的 json? [关闭]
【发布时间】:2021-09-02 16:00:45
【问题描述】:

我想在 python 中解码这个 json,但我找不到任何合适的工作文档。

{
  "users" : {
    "-MiZDzE6eV_oy-k7liD7" : {
      "lat" : 22.992344005762106,
      "lon" : 88.39171958538499,
      "name" : "user1",
      "time" : "7:29:57,Time In,Thu Sep 02 2021 07:29:57 GMT+0530 (India Standard Time)"
    },
    "-MiZeikP4SFbwAU2-ubt" : {
      "lat" : 22.992344005762106,
      "lon" : 88.39171958538499,
      "name" : "user2",
      "time" : "9:31:9,Time In,Thu Sep 02 2021 09:31:09 GMT+0530 (India Standard Time)"
    }
  }
}

像这样
name = json
中的每个名称值 lat = 来自 json
的每个 lat 值 等等..

我已经试过了

import json
import requests

url = "someurl"
response = requests.get(url)
json = json.loads(response.text)
user = json["users"]
print(user["name"])

【问题讨论】:

  • 请在下面查看我的答案,但我确实想花一点时间指出您的变量 json 覆盖了您在第 1 行导入的模块 json。这会给您带来很多困惑稍后,最好只是重命名它。只需调用它json_ 就足够了

标签: python json


【解决方案1】:

解构 JSON(这是我认为您的意思而不是解码)是 list comprehensions 的绝佳候选者

可以这样做:

names = [user['name'] for user in json['user'].values()]
lat = [user['lat'] for user in json['user'].values()]

如果你有很多这样的事情要做一个正常的循环可能是你更好的选择。

奖励:请求将为您转换 json。 json = response.json()

【讨论】:

    【解决方案2】:

    你只需要这样做:

    import requests
    url = "example.com"
    data = requests.get(url).json()
    # There are 2 Indexes in the JSON output,
    # 1 Being -MiZDzE6eV_oy-k7liD7
    # and the other being: -MiZeikP4SFbwAU2-ubt
    ind2 = data["-MiZeikP4SFbwAU2-ubt"] # For the second index
    ind1 = data["-MiZDzE6eV_oy-k7liD7"]
    # Now we Parse what we need from the Seperate Indexes
    user1 = ind1["name"]
    user2 = ind2["name"]
    print(user1)
    print(user2)
    

    【讨论】:

    • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
    猜你喜欢
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    相关资源
    最近更新 更多