简体   繁体   中英

meaning of the returned list of python json

I'm new to python so I really don't know the language very well.

the following example was taken from here http://docs.python.org/library/json.html

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

what does the u mean? and how do i know which elements are available in the dictionary?

It's a unicode . Iterating over the dict yields its keys:

for k in D:
  print k, D[k]

Ignacio's answer a bit more verbose (no upvotes to me)

u'something' means that 'something' is a unicode string, and not for instance an ascii string. Generally text is encoded as 8-bit characters, and you need an encoding to properly interpret/display it. Unicode is 16-bit and doesn't need seperate encodings for the various locale dependent characters.

In a dictionary (enclosed by {}) the key is the part before the ":" and the value comes after.

You got a list, with elements:

  • foo, a Unicode string
  • a dictionary containing:
    • a key (unicode) "bar", and accessible through that key a list with values
      • unicode string baz,
      • None
      • a float 1.0
      • an integer 2

The python type function can be useful here.

>>> import json
>>> data = json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
>>> data
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
>>> type(data)
<type 'list'>
>>> type(data[0])
<type 'unicode'>
>>> type(data[1])
<type 'dict'>

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