Python: json.loads returns items prefixing with ‘u’

Posted on

Question :

Python: json.loads returns items prefixing with ‘u’

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 = {}
try:
    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
            else:
                da = {}
                da[key] = value
        mail_accounts.append(da)
except Exception, err:
    sys.stderr.write('Exception Error: %s' % str(err))

print mail_accounts
Asked By: janeh

||

Answer #1:

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.

Answered By: Ned Batchelder

Answer #2:

Everything is cool, man. The ‘u’ is a good thing, it indicates that the string is of type Unicode in python 2.x.

http://docs.python.org/2/howto/unicode.html#the-unicode-type

Answered By: Aman

Answer #3:

The d3 print below is the one you are looking for (which is the combination of dumps and loads) 🙂

Having:

import json

d = """{"Aa": 1, "BB": "blabla", "cc": "False"}"""

d1 = json.loads(d)              # Produces a dictionary out of the given string
d2 = json.dumps(d)              # Produces a string out of a given dict or string
d3 = json.dumps(json.loads(d))  # 'dumps' gets the dict from 'loads' this time

print "d1:  " + str(d1)
print "d2:  " + d2
print "d3:  " + d3

Prints:

d1:  {u'Aa': 1, u'cc': u'False', u'BB': u'blabla'}
d2: "{"Aa"": 1, ""BB"": ""blabla"", ""cc"": ""False""}""

Leave a Reply

Your email address will not be published.