开发者

meaning of the returned list of python json

I'm new to python so I really don't k开发者_如何学Cnow 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'>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜