【问题标题】:Python requests response Json does not convert to dictionaryPython请求响应Json不转换为字典
【发布时间】:2021-06-10 02:28:35
【问题描述】:

我得到一个嵌套的 Json 作为请求响应,试图精确到 name 字段。然而,在将其转换为 Json 之后,本应是字典的内容变成了字符串。您能否帮助指出我做错了什么以及如何处理?非常感谢。

来自打印response.json()的示例结果:

{'subject': 'order', 'id':20, 'info':{"result":"record","name":"orderrecords", "items":[{"name":"apple","type":"food"},{"name":"orange","type":"food"}]}

我试过了:

response= requests.get("url")
info= response.json()
print (type(info["items"]) #it is str here

我想要实现的是拥有一个值为“名称”的字典,其中包含项目的字典作为键,而“类型”作为值。比如 {"apple":"food", "orange": "food"}

【问题讨论】:

  • 你提供了无效的 json

标签: python json python-3.x dictionary python-requests


【解决方案1】:

当 json 结果打印在控制台上时,预期结果为 '.但是 object/variable(info) 可能是 json 格式。

首先得到的结果有语法问题。请添加花括号:

info = {'subject': 'order', 'id':20, 'info':{"result":"record","name":"orderrecords", "items":[{"name":"apple","type":"food"},{"name":"orange","type":"food"}]}}

Even if the object is dictionary:

print(info["info"]["items"][0])
print(info["info"]["items"][1])

如果结果是 json,那么请按照上述建议导入 json 并加载

【讨论】:

    【解决方案2】:

    返回的json 对象不是一个有效的对象,因为json 应该有" 而不是'

    您可以使用replace()' 替换为",然后转换为json 对象:

    import json
    data = '''{'subject': 'order', 'id':20, 'info':{"result":"record","name":"orderrecords", "items":[{"name":"apple","type":"food"},{"name":"orange","type":"food"}]}}''' # there is also a missing } in the end
    data = data.replace("'", '"')
    data_json = json.loads(data)
    res = {elt["name"] : elt["type"] for elt in data_json["info"]["items"]}
    print(res)
    

    输出:

    {'apple': 'food', 'orange': 'food'}
    

    注意:这也将替换作为数据的一部分存在的任何单引号(如果有)。

    【讨论】:

      猜你喜欢
      • 2022-11-03
      • 2011-01-29
      • 2019-09-28
      • 2020-05-20
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      相关资源
      最近更新 更多