我正在使用requests
模块。并且,返回的数据是unicode,其中包含来自服务器的响应(字典)。有没有办法漂亮打印无字典词典?
返回的响应如下所示:
u'<<200:{"id":"12345","key_x":"41341e2277422","name":"xyz","key_y":"000566b8-1f52-5b38c","marked_for_removal":false,"max_capacity":3831609642556,"total_capacity":0,"total_reserved_capacity":0}'
或者这个:
u'>>GET https://x.x.x.x:8888/services/rest/abc : {'headers': {'content-type': 'application/json;charset=UTF-8', 'Accept': 'application/json, text/javascript, */*; q=0.01'}, 'params': {}, 'timeout': 30, 'verify': False}'
我想以下列方式打印它:
u'<<200:
{"id":"12345",
"key_x":"41341e2277422",
"name":"xyz",
"key_y":"000566b8-1f52-5b38c",
"marked_for_removal":false,
"max_capacity":3831609642556,
"total_capacity":0,
"total_reserved_capacity":0}'
即。中间的json应该被格式化,字符串可以保持不变。
我已尝试将数据转换为字符串并打印,但这并不起作用。
import pprint
pprint.pprint(data.encode('utf-8'), width=1)
答案 0 :(得分:1)
response
属于str
类型 - 包含HTTP状态代码和实际的JSON数据结构。
import json
import pprint
# response is coming from requests, most likely Content-Type: text/plain
# separate the status code '200' from the actual JSON data
status = response[:6]
data = response[6:]
if '200' not in status:
# Bail out, got an error
exit(0)
parsed = json.loads(data.encode('utf-8'))
# Print output
print status
# Using pprint
pprint.pprint(parsed)