gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:36:46 27 4
gpt4 key购买 nike

我正在使用 Flask-Python 创建一个 REST API。其中一个 url (/uploads) 接受(一个 POST HTTP 请求)和一个 JSON '{"src":"void", "settings":"my settings"}'。我可以单独提取每个对象并编码为字节字符串,然后可以使用 python 中的 hashlib 对其进行哈希处理。但是,我的目标是获取整个字符串然后进行编码,使其看起来像...myfile.encode('utf-8')。打印 myfile 显示如下 >> {u'src':u'void', u'settings':u'my settings'}, 反正我可以把上面的 unicoded 字符串编码成 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

最佳答案

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

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

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

python 2

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

jsonContent = json.dumps(request.json, ensure_ascii=True)
guid_object = hashlib.sha1(jsonContent)

python 3

然而,在 Python 3 中,这将不再有效。事实上,json.dumps() 在 Python 3 中返回 unicode,即使 unicode 字符串中的所有内容都是 ASCII。但是 hashlib.sha1 只适用于 bytes。您需要明确转换,即使您只需要 ASCII 编码:

jsonContent = json.dumps(request.json, ensure_ascii=True)
guid_object = hashlib.sha1(jsonContent.encode('ascii'))

这就是 Python 3 是一门更好的语言的原因:它迫使您对所使用的文本更加明确,无论是 str (Unicode) 还是 bytes。这避免了很多很多问题。

关于python - 如何在 python 中将 unicode 字符串(来自 JSON 的字符串)编码为 'utf-8'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31658603/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com