django remove unicode from query result

冷暖自知 提交于 2019-12-04 20:02:48

Try this:

>>> import json
>>> data=[{'total': 1744, 'name': u'x'}, {'total': 13, 'name': u'm'}, {'total': 126, 'name': u'n'}]
>>> json.dumps([i.values()[::-1] for i in data])
'[["x", 1744], ["m", 13], ["n", 126]]'
>>> 

You can't rely on the order in which keys will come out of a dictionary (e.g. the order of the values in i.values()), so your best bet is to write something like this:

m = []
for i in date:
    m.append([i['name'], i['total']])

NB: you also mean to be iterating date, not m, which would be empty in this example. Corrected in my code here.

Use str().

>>> def byte_string(x):
...   return str(x) if isinstance(x, unicode) else x
...

>>> [[byte_string(x) for x in row] for row in d]
[[1744, 'x'], [13, 'm'], [126, 'n']]

Note that this code will bomb if you data contains non-ascii string.

I used str(jsonVal) to solve this issue. Removed the requirement to use post processing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!