Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the u's when I use json.loads? [duplicate]

I've been writing a Python script to parse JSON information from the Soundcloud API, and I was just wondering what the "u"'s are when I use json.loads( val ) and how to store the JSON information to an object without the u's?

i.e. why are there u's in this:

>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]

See the "Decoding JSON" section here to understand what I mean further:

http://docs.python.org/library/json.html

like image 709
ZenLikeThat Avatar asked Feb 08 '12 20:02

ZenLikeThat


People also ask

What is U in JSON?

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.

Can JSON have duplicate values?

We can have duplicate keys in a JSON object, and it would still be valid. The validity of duplicate keys in JSON is an exception and not a rule, so this becomes a problem when it comes to actual implementations.

What does JSON loads () return?

loads() takes in a string and returns a json object.

Can a JSON object contain duplicate keys?

I've done some research and I understood that "duplicate" keys in JSON are legal, but different parsers act differently in handling this. How can I avoid the use of duplicate keys or, alternatively, make sure the schema validates the value for all duplicated keys? Hermann.


2 Answers

Unicode strings. See the Python Tutorial.

In Python source code, Unicode literals are written as strings prefixed with the ‘u’ or ‘U’ character: u'abcdefghijk'.

— Unicode Literals in Python Source Code

like image 113
Francis Avila Avatar answered Sep 21 '22 14:09

Francis Avila


the u's are there to indicate that a Unicode string is supposed to be created.

It sucks that json.dump converts strings to unicode strings and leaves no trace of having done that, because then json.load can't convert back.

To convert to string objects, use PyYAML:

>>> import yaml
>>> yaml.load('["foo", {"bar":["baz", null, 1.0, 2]}]')
>>> ['foo', {'bar': ['baz', None, 1.0, 2]}]

But careful! If for some reason you json.dumped an object containing object strings and unicode strings, yaml will load everything as object strings (though that's json.dump's fault really)

like image 21
Alexandre Holden Daly Avatar answered Sep 17 '22 14:09

Alexandre Holden Daly