python - Python 请求响应以 JSON 格式打印 U' 被添加到结果中
问题描述
我想u
从结果中删除(unicode 值)。其他工具不是以 JSON 格式读取它。
import requests
import json
headers={
"accept": "application/json",
"content-type": "application/json"
}
test_urls = ['https://google.com']
def return_json(url):
try:
response = requests.get(url,headers=headers)
# Consider any status other than 2xx an error
if not response.status_code // 100 == 2:
return "Error: Unexpected response {}".format(response)
json_obj = response.json()
return json_obj
except requests.exceptions.RequestException as e:
# A serious problem happened, like an SSLError or InvalidURL
return "Error: {}".format(e)
for url in test_urls:
print "Fetching URL '{}'".format(url)
print return_json(url)
结果:
{u'rows': [{u'timestamp': 1585924500001L, u'RAM_': 1000, u'Allocated': 4000.78, u'queue': 0, u'Details': u'Connected': 2, u'Queue': 0, u'EventsQueue': 0}]
我想要没有u
价值的结果
解决方案
您可以使用encode()
方法将 unicode 字符串转换为 ascii 字符串,如下所示:
import requests
import json
headers={
"accept": "application/json",
"content-type": "application/json"
}
test_urls = ['http://www.mocky.io/v2/5185415ba171ea3a00704eed']
def return_json(url):
try:
response = requests.get(url,headers=headers)
# Consider any status other than 2xx an error
if not response.status_code // 100 == 2:
return "Error: Unexpected response {}".format(response)
json_obj = response.json()
return json_obj
except requests.exceptions.RequestException as e:
# A serious problem happened, like an SSLError or InvalidURL
return "Error: {}".format(e)
for url in test_urls:
print("Fetching URL '{0}'".format(url))
ret = return_json(url)
ret = {unicode(k).encode('ascii'): unicode(v).encode('ascii') for k, v in ret.iteritems()}
print(ret)
推荐阅读
- python - 匹配文件系统路径但不匹配 Python 中的 URL
- uwp - 使用多个键盘时获取 UWP 窗口上的键事件的键盘设备 ID
- apache-kafka - 哪些数据源可以用作 Event Hubs 和 Apache Kafka 等流服务的来源?
- r - 创建包时的 R 环境问题
- javascript - 如何防止 iframe 在新标签页中打开
- python - 将 PyQt QLineEdit 文本作为参数传递
- airflow - 支持手动和定时执行
- asynchronous - 是否可以在不消耗其输出的情况下检查未来是否准备就绪?
- blender - 使用纹理绘画或重量绘画时,Blender 冻结
- css - 无法在左下角放置绝对定位的图像