简体   繁体   中英

avoid utf-8 on python

I'm using a python code to get data from my server. However, I keep getting a "u" as a prefix to each key in the JSON

as follows:

"{u'BD': 271, u'PS': 48, u'00': 177, u'CA': 5, u'DE': 15, u'FR': 18, u'UM': 45, u'KR': 6, u'IL': 22181, u'GB': 15}"

My python code is as follows:

from json import dumps
ans = select something from the database    
json.dumps(ans)

does any know how to avoid it?

The u'' means the value is a unicode literal. Everything is working as intended, you don't need to get rid of those.

JSON is a standard that supports Unicode values natively, and thus the json module accepts unicode strings when converting a Python value to JSON:

>>> import json
>>> ans={u'BD': 271, u'PS': 48, u'00': 177, u'CA': 5, u'DE': 15, u'FR': 18, u'UM': 45, u'KR': 6, u'IL': 22181, u'GB': 15}
>>> json.dumps(ans)
'{"BD": 271, "PS": 48, "00": 177, "IL": 22181, "UM": 45, "KR": 6, "CA": 5, "DE": 15, "FR": 18, "GB": 15}'

I think something got mixed up here. The result you've posted looks like a Python representation of a dict. To be precise: json.dumps returns a string, so its result should be enclosed in quotes, like this:

>>> import json
>>> json.dumps({'foo': 'bar'})
'{"foo": "bar"}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM