Python Unicode API响应抛出错误'';ascii';编解码器可以';t编码字符u'\u2019&x27;在位置22462';

Python Unicode API响应抛出错误'';ascii';编解码器可以';t编码字符u'\u2019&x27;在位置22462';,python,unicode,utf-8,Python,Unicode,Utf 8,我正在进行一个API调用,响应具有unicode字符。将此响应加载到文件会引发以下错误: 'ascii' codec can't encode character u'\u2019' in position 22462 我尝试了解码和编码的所有组合(“utf-8”) 代码如下: url = "https://%s?start_time=%s&include=metric_sets,users,organizations,groups" % (api_path, start_epoch)

我正在进行一个API调用,响应具有unicode字符。将此响应加载到文件会引发以下错误:

'ascii' codec can't encode character u'\u2019' in position 22462
我尝试了解码和编码的所有组合(“utf-8”)

代码如下:

url = "https://%s?start_time=%s&include=metric_sets,users,organizations,groups" % (api_path, start_epoch)
while url != None and url != "null" :
json_filename = "%s/%s.json" % (inbound_folder, start_epoch)
try:
    resp = requests.get(url,
                        auth=(api_user, api_pwd),
                        headers={'Content-Type': 'application/json'})

except requests.exceptions.RequestException as e:
    print "|********************************************************|"
    print e
    return "Error: {}".format(e)
    print "|********************************************************|"
    sys.exit(1)

try:
    total_records_extracted = total_records_extracted + rec_cnt
    jsonfh = open(json_filename, 'w')
    inter = resp.text
    string_e = inter#.decode('utf-8')
    final = string_e.replace('\\n', ' ').replace('\\t', ' ').replace('\\r', ' ')#.replace('\\ ',' ')
    encoded_data = final.encode('utf-8')
    cleaned_data = json.loads(encoded_data)
    json.dump(cleaned_data, jsonfh, indent=None)
    jsonfh.close()
except ValueError as e:
    tb = traceback.format_exc()
    print tb
    print "|********************************************************|"
    print  e
    print "|********************************************************|"
    sys.exit(1)
很多开发者都面临着这个问题。许多地方要求使用
.decode('utf-8')
或在python顶部使用
*.\ucode:utf-8.*.

这仍然于事无补

有人能帮我解决这个问题吗

以下是跟踪:

Traceback (most recent call last):
File "/Users/SM/PycharmProjects/zendesk/zendesk_tickets_api.py", line 102, in main
cleaned_data = json.loads(encoded_data)
File "/Users/SM/anaconda/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/Users/SM/anaconda/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/SM/anaconda/lib/python2.7/json/decoder.py", line 380, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Invalid \escape: line 1 column 2826494 (char 2826493)

|********************************************************|
Invalid \escape: line 1 column 2826494 (char 2826493)
text
属性是一个Unicode字符串,使用HTTP头中猜测的请求模块可能正在使用的任何编码从原始字节解码

你可能不想这样;JSON对编码应该是什么有自己的想法,因此您应该让JSON解码器通过从
resp.content
获取原始响应字节,并将它们直接传递给
JSON.loads

更重要的是,请求有一个快捷方式来执行相同的操作:
resp.json()

尝试在JSON字符串文本格式的输入上执行此操作是一个坏主意:您将错过一些有效转义,并错误地取消转义其他转义。您的实际错误与Unicode完全无关,这是因为此替换正在损坏输入。例如,考虑输入JSON:

{"message": "Open the file C:\\newfolder\\text.txt"}
更换后:

{"message": "Open the file C:\ ewfolder\ ext.txt"}
这显然不是有效的JSON

与其尝试对JSON编码的字符串进行操作,不如让
JSON
解码输入,然后过滤结构化输出中的任何字符串。这可能涉及使用递归函数深入到数据的每一层,寻找要过滤的字符串。乙二醇

def clean(data):
    if isinstance(data, basestring):
        return data.replace('\n', ' ').replace('\t', ' ').replace('\r', ' ')
    if isinstance(data, list):
        return [clean(item) for item in data]
    if isinstance(data, dict):
        return {clean(key): clean(value) for (key, value) in data.items()}
    return data

cleaned_data = clean(resp.json())

为了确定解释器停在哪一行?请提供完整的堆栈跟踪。您正在使用请求吗?如果是这样,只需使用
resp.json()
如果需要json,请添加问题的回溯以保留格式。注释中不可读。
inter
是如何初始化的?错误代码暗示它是Unicode字符串,并且您正在使用Python 2。在Python 2上,Unicode字符串使用默认的
ascii
编解码器隐式编码为字节字符串,因为
.decode()
仅对字节字符串有效。请提供一个。这有助于我清理转义字符。但是,我还希望将unicode数据写入下游数据库。当我尝试读取此代码编写的文件时,它会遇到unicode字符,例如6月23日的
XTREME\u201325
json。加载将
\u2013
输入转换为字符U+2013 En-Dash
很好。
{"message": "Open the file C:\ ewfolder\ ext.txt"}
def clean(data):
    if isinstance(data, basestring):
        return data.replace('\n', ' ').replace('\t', ' ').replace('\r', ' ')
    if isinstance(data, list):
        return [clean(item) for item in data]
    if isinstance(data, dict):
        return {clean(key): clean(value) for (key, value) in data.items()}
    return data

cleaned_data = clean(resp.json())