如何将unicode字符串(来自JSON的字符串)编码为' utf-8'在python?

时间:2015-07-27 16:35:50

标签: python json python-2.7 unicode utf-8

我正在使用Flask-Python创建REST API。其中一个网址(/ uploads)接收(POST HTTP请求)和JSON' {" src":" void","设置" :"我的设置"}'。我可以单独提取每个对象并编码为一个字节字符串,然后可以使用python中的hashlib进行哈希处理。但是,我的目标是获取整个字符串然后进行编码,使其看起来像...... myfile.encode(' utf-8')。打印myfile显示如下>> {u' src':u' void',u'设置':我的设置'},无论如何我可以使用上面的单字符串然后编码为utf-8为hashlib.sha1的字节序列(mayflies.encode(' uff-8')。请告诉我更多说明。提前致谢。

fileSRC = request.json['src']
fileSettings = request.json['settings']

myfile = request.json
print myfile

#hash the filename using sha1 from hashlib library
guid_object = hashlib.sha1(fileSRC.encode('utf-8')) // this works however I want myfile to be encoded not fileSRC
guid = guid_object.hexdigest() //this works 
print guid

1 个答案:

答案 0 :(得分:1)

正如您在评论中所说,您使用以下方法解决了您的问题:

jsonContent = json.dumps(request.json)
guid_object = hashlib.sha1(jsonContent.encode('utf-8'))

但重要的是要理解为什么会这样。烧瓶sends you unicode() for non-ASCII, and str() for ASCII。使用JSON转储结果将为您提供一致的结果,因为它抽象出内部Python表示,就像您只有unicode()一样。

Python 2

在Python 2(您正在使用的Python版本)中,您不需要.encode('utf-8'),因为ensure_ascii的{​​{1}}的默认值为json.dumps()。当您将非ASCII数据发送到True时,它将使用JSON转义序列实际转储ASCII:无需编码为UTF-8。此外,由于Zen of Python表示“明确比隐含更好”,即使json.dumps()已经ensure_ascii,您也可以指定它:

True

Python 3

然而,在Python 3中,这将不再起作用。 Inded,jsonContent = json.dumps(request.json, ensure_ascii=True) guid_object = hashlib.sha1(jsonContent) 在Python 3中返回json.dumps(),即使unicode字符串中的所有内容都是ASCII。但unicode仅适用于hashlib.sha1。您需要明确转换,即使您只需要ASCII编码:

bytes

这就是为什么Python 3是一种更好的语言:它会强迫您更明确地使用您使用的文本,无论是jsonContent = json.dumps(request.json, ensure_ascii=True) guid_object = hashlib.sha1(jsonContent.encode('ascii')) (Unicode)还是str。这可以避免许多问题。