【问题标题】:How to encode a unicode string (ones from JSON) to 'utf-8' in python?如何在python中将unicode字符串(来自JSON的字符串)编码为'utf-8'?
【发布时间】:2015-10-17 23:08:03
【问题描述】:

我正在使用 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

【问题讨论】:

  • 澄清:您是否要使 json 成为字符串并对其进行哈希处理?
  • 您好,感谢您的回复。我从你的问题中得到了答案,它现在有效。非常感谢。
  • 我使用了 ...jsonContent = json.dumps(request.json)..then guid_object = hashlib.sha1(jsonContent.encode('utf-8'))。现在可以了。

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


【解决方案1】:

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

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'),因为json.dumps()ensure_ascii 的默认值是True。当您向json.dumps() 发送非ASCII 数据时,它将使用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 中,这将不再有效。 Inded,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。这样可以避免很多很多问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-21
    • 2016-05-16
    • 2011-08-09
    • 2016-09-02
    • 2016-01-11
    • 1970-01-01
    • 2019-09-15
    • 2016-10-01
    相关资源
    最近更新 更多