0

我正在使用requests模块。而且,返回的数据是包含来自服务器的响应(字典)的 unicode。有没有办法漂亮地打印 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)
4

1 回答 1

1

responseis of strtype - 包含 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)
于 2018-03-09T06:53:47.643 回答