我的 PYCURL 请求遇到问题。 我在服务器上的 json 文件采用 utf-8 编码,如下所示:
{
"address" : "123 rue de Labège"
}
我使用 PYCURL 获取此 json 并将其复制到我的计算机上的新文件中。 我使用 Python 2.7,这是我的 PYCURL 设置:
def setup(self, _url, _method, _login, _passwd, _path, *args, **kwargs):
self.curl = pycurl.Curl()
self.url = 'https://%s:%d/' % (self.ip, self.port) + _url
self.method = _method
self.userpwd = '%s:%s' % (_login, _passwd)
self.path = _path
self.curl.setopt(pycurl.URL, self.url)
curl_method = {
"GET": pycurl.HTTPGET,
"POST": pycurl.POST
}
if self.method in curl_method:
self.curl.setopt(curl_method[self.method], 1)
else:
self.curl.setopt(pycurl.CUSTOMREQUEST, self.method)
self.curl.setopt(pycurl.SSL_VERIFYPEER, 0)
self.curl.setopt(pycurl.SSL_VERIFYHOST, 0)
self.curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
self.curl.setopt(pycurl.USERPWD, self.userpwd)
if _url == 'MY_FILE_JSON':
filename = 'file.json'
self.file = open(self.path + filename, 'wb')
self.curl.setopt(pycurl.WRITEDATA, self.file)
问题出在我收到的文件中:
{
"address" : "123 rue de Lab\u00e8uge"
}
我不明白为什么 PYCURL 将我的“è”编码为\u00e8。 setopt 和 PYCURL 是否有任何选项可以强制它打印好字符?
最佳答案
实际上这是完全正确的,一旦你对变量属性进行打印
,你就可以看到它打印得很好。
这就是 Python 内部处理 Unicode 字符串的方式。一旦 PycURL 收到文件,它将被转换为适合该属性的任何类型。在您的情况下,这是一个 Unicode 字符串。
检查this article获取更多信息。
回顾一下,如果您这样做:
>>> test = u'123 rue de Lab\u00e8uge'
>>> print(test)
123 rue de Labèuge
在这里您可以看到我创建了一个 Unicode 字符串(以 u
开头)。
关于python - PYCURL获取json文件存在utf-8编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39787756/