django remove unicode from query result

烂漫一生 提交于 2019-12-06 15:03:02

问题


Django query gives me below output format,but i want below format

data=`[{'total': 1744, 'name: u'x'}, {'total': 13, 'name': u'm'}, {'total': 126, 'role': name'n'}]`
m=[]
for i in data:
   m.append(i.values())

print m it give me output

[[1744,u'x'], [13,u'm'], [126,u'n']]

but i need output in how to remove unicode symbol from output

[['x',1744], ['m',13], ['n',126]]

how to do this ?

Thanks in advance


回答1:


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]]'
>>> 



回答2:


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.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/5263159/django-remove-unicode-from-query-result

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