首页 > 解决方案 > 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价值的结果

标签: pythonurlunicodepython-requests

解决方案


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

推荐阅读