开发者

django remove unicode from query result

开发者 https://www.devze.com 2023-02-16 05:31 出处:网络
Django query gives me below outputformat,but i want below format data=`[{\'total\': 1744, \'name: u\'x\'}, {\'total\': 13, \'name\': u\'m\'}, {\'total\': 126, \'role\': name\'n\'}]`

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消