简体   繁体   English

Python 请求响应 Json 不转换为字典

[英]Python requests response Json does not convert to dictionary

I get a nested Json as request response, trying to exact the name field.我得到一个嵌套的 Json 作为请求响应,试图精确name字段。 However after converting it to Json, what supposed to be a dictionary turned to a string.然而,在将其转换为 Json 后,本应是字典的内容变成了字符串。 Could you please help pointing out what I did wrong and how to handle this?您能否帮助指出我做错了什么以及如何处理? Many thanks.非常感谢。

sample result from print response.json() :来自 print response.json()的示例结果:

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

I tried with:我试过:

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

What I am looking to achieve is having a dictionary with value of "name", the one with in items, as keys and the "type" as value.我想要实现的是拥有一个值为“名称”的字典,其中包含项目的字典作为键,而“类型”作为值。 Like {"apple":"food", "orange": "food"}像 {"apple":"food", "orange":"food"}

The json object returned is not a valid one as json should have " and not ' .返回的json object 不是有效的,因为json应该有"而不是'

You can use replace() to replace ' with " and then convert to json object:您可以使用replace()'替换为" ,然后转换为json object:

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)

Output: Output:

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

Note: This will also replace any single quotes which are present as part of data if any.注意:这也将替换作为数据一部分存在的任何单引号(如果有)。

When the json result is printed on console expected to have result in '.当 json 结果打印在控制台上时,预计结果为 '. But the object/variable(info) might have the json format.但是对象/变量(信息)可能具有 json 格式。

First of all the result obtained has syntax issue.首先获得的结果有语法问题。 please add curly braces:请添加花括号:

info = {'subject': 'order', 'id':20, 'info':{"result":"record","name":"orderrecords", "items":[{"name":"apple","type":"food"},{"name":"orange","type":"food"}]}} 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:即使 object 是字典:

print(info["info"]["items"][0]) print(info["info"]["items"][1])打印(信息[“信息”][“项目”][0]) 打印(信息[“信息”][“项目”][1])

if the result is in json then please import json & load as above suggestion如果结果在 json 然后请导入 json 并按上述建议加载

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

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