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'', u'p': u'aaaa'}, {u'i': u'', u'p': u'bbbb'}...

How is JSON adding this unicode char? What’s the best way to remove it?

mail_accounts = []
da = {}
    s = '[{"i":"","p":"aaaa"},{"i":"","p":"bbbb"},{"i":"","p":"ccccc"},{"i":"","p":"ddddd"},{"i":"","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
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.

Answered By: Aman

Answer #3:

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


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


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. Required fields are marked *