我想从结果中删除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)