将 JSON 响应转换为 python 对象

Converting JSON response to python object

我想将 HTTP GET 响应(我正在使用 requests library)转换为 python 对象。这是我的代码:

# Full, pure, response
response = requests.get(url)

# Getting request data/content represented in byte array
content = response.content

# Byte array to string
data = content.decode('utf8')


# This line causes "ValueError: malformed node or string: <_ast.Name object at 0x7f35068be128>"
#data = ast.literal_eval(data)

# I tried this also but data is still string after those 2 lines
data = json.dumps(data)
data = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))

您可以使用 content = response.json() 将响应作为字典获取,然后将 content 直接传递给 json.loads(假设您的响应是 json )

# Full, pure, response
response = requests.get(url)

# Getting response as dictionary
content = response.json()

#Loading dictionary as json
data = json.loads(content, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))