janeh janeh - 4 years ago 650
Python Question

Python: json.loads returns items prefixing with 'u'

OK, I'll be receiving a JSON encoded string form Obj-C, and I am decoding a dummy string (for now) like the code below. My output comes out with character 'u' prefixing each item:

[{u'i': u'imap.gmail.com', u'p': u'aaaa'}, {u'i': u'333imap.com', u'p': u'bbbb'}...
How is JSON adding this unicode char? What's the best way to remove it?

mail_accounts = []
da = {}
s = '[{"i":"imap.gmail.com","p":"aaaa"},{"i":"imap.aol.com","p":"bbbb"},{"i":"333imap.com","p":"ccccc"},{"i":"444ap.gmail.com","p":"ddddd"},{"i":"555imap.gmail.com","p":"eee"}]'
jdata = json.loads(s)
for d in jdata:
for key, value in d.iteritems():
if key not in da:
da[key] = value
da = {}
da[key] = value
except Exception, err:
sys.stderr.write('Exception Error: %s' % str(err))

print mail_accounts

Answer Source

The u- prefix just means that you have a Unicode string. When you really use the string, it won't appear in your data. Don't be thrown by the printed output.

For example, try this:

print mail_accounts[0]["i"]

You won't see a u.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download