在python中将unicode json转换为普通的json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36954511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert unicode json to normal json in python
提问by Sanjiban Bairagya
I got the following json: {u'a': u'aValue', u'b': u'bValue', u'c': u'cValue'}
by doing request.json
in my python code. Now, I want to convert the unicode json to normal json, something which should like this: {"a": "aValue", "b": "bValue", "c": "cValue"}
. How do I get this done, without having to do any manual replacements? Please help.
我得到了以下 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"}
. 我如何完成这项工作,而无需进行任何手动更换?请帮忙。
回答by nirprat
{u'a': u'aValue', u'b': u'bValue', u'c': u'cValue'} is a dictionary which you are calling as unicode json. Now, in your language if you want a regular json from this then just do something like this:
{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
The output will be {"a": "aValue", "c": "cValue", "b": "bValue"}
输出将是 {"a": "aValue", "c": "cValue", "b": "bValue"}
回答by deusxmachine
For python 2.x
对于 python 2.x
import yaml
import json
json_data = yaml.load(json.dumps(request.json()))
Now this json_data can be used as a json and can have list of json as well.
现在这个 json_data 可以用作 json 并且可以有 json 列表。
回答by Natecat
You can use a list comprehension to encode all of the keys and values as ascii like this:
您可以使用列表理解将所有键和值编码为 ascii,如下所示:
dict([(k.encode('ascii','ignore'), v.encode('ascii','ignore')) for k, v in dct.items()])
Note: There generally isn't much benefit to not having your data in unicode, so unless you have a specific reason not to have it in unicode, then I would leave it.
注意:不将数据放在 unicode 中通常没有太大好处,因此除非您有特定原因不使用 unicode 中的数据,否则我会保留它。
回答by Noah F. SanTsorvutz
A library available in PyPi may be helpful, see: unidecode.
PyPi 中可用的库可能会有所帮助,请参阅:unidecode。
It is intended to transform European characters with diacriticals (accents) to their base ASCII characters, but it does just as well when the unicode character is already in the ASCII range.
它旨在将带有变音符号(重音)的欧洲字符转换为它们的基本 ASCII 字符,但当 unicode 字符已经在 ASCII 范围内时,它也能正常工作。
from unicode import unidecode
从 unicode 导入 unidecode
def fUnUn(sOrU): return unidecode(sOrU).encode('ascii') if type(sOrU) is unicode else sOrU
def fUnUn(sOrU): 返回 unidecode(sOrU).encode('ascii') 如果 type(sOrU) 是 unicode else sOrU
sASCII = fUnUn(u'ASCII')
sASCII = fUnUn(u'ASCII')