在python中将unicode json转换为普通的json

San*_*gya 8 python unicode json

我得到了以下json:{u'a': u'aValue', u'b': u'bValue', u'c': u'cValue'}通过request.json我的python代码.现在,我想将unicode json转换为普通的json,这应该是这样的:{"a": "aValue", "b": "bValue", "c": "cValue"}.如何在不进行任何手动更换的情况下完成此操作?请帮忙.

nir*_*rat 13

{u'a':u'aValue',u'b':u'bValue',u'c':u'cValue'}是一个字典,你称之为unicode json.现在,用你的语言,如果你想要一个普通的json,那么就这样做:

x={u'a': u'aValue', u'b': u'bValue', u'c': u'cValue'}
y=json.dumps(x)
print y
Run Code Online (Sandbox Code Playgroud)

输出将为{"a":"aValue","c":"cValue","b":"bValue"}

  • Json.dumps不返回字典.它只将它转换为字符串. (12认同)

deu*_*ine 8

对于python 2.x

import yaml
import json
json_data = yaml.load(json.dumps(request.json()))
Run Code Online (Sandbox Code Playgroud)

现在,此json_data可用作json,并且还可以包含json列表。


Nat*_*cat 1

您可以使用列表理解将所有键和值编码为 ascii,如下所示:

dict([(k.encode('ascii','ignore'), v.encode('ascii','ignore')) for k, v in dct.items()])
Run Code Online (Sandbox Code Playgroud)

注意:通常不将数据保存在 unicode 中并没有多大好处,因此除非您有特定原因不将其保存在 unicode 中,否则我会保留它。