将JSON响应转换为python对象

时间:2019-05-17 06:30:11

标签: python json http response

我想将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()))

1 个答案:

答案 0 :(得分:2)

您可以使用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()))