1

I just have a question regarding SimpleJSON's documentation. Is it implicit understood that functions for example .get() can be used without the need of the author to document it? Or is it something regarding how python works instead for how SimpleJSON works, thus no need to write it down? I got really frustrated when I couldn't find in the documentation that get() could be used.

http://simplejson.readthedocs.org/en/latest/index.html

For example following code

import simplejson as json
import urllib2


req = urllib2.Request("http://example.com/someJson")
opener = urllib2.build_opener()
f = opener.open(req)

data = json.load(f)

print data.get('results')

I couldn't find anywhere in the documentation about this function.

starcorn
  • 8,261
  • 23
  • 83
  • 124

1 Answers1

3

json.load() will deserialize your JSON document and return a Python object.

So I'd say that data is a dict and here's the .get() documentation.

What Python object json.load() will return depends on the input that you'll give him.

Example with json.loads() which is the same thing, but on strings:

>>> json.loads('[1, 2, "dog"]')
[1, 2, 'dog']
>>> json.loads('{"animals": ["cat", "dog"], "4": 4}') 
{'animals': ['cat', 'dog'], '4': 4}
>>> json.loads('"dog"') 
'dog'

As you see there are a endless number of possiblities (since they could also be nested).

If you don't know the format of the json file you're going to parse then yes, you should come up with some hack to understand its structure, but it would be best to know in advance how is structured. Since your going to use its information you should probably know that (or be allowed to know that).


I see that you've already found out, but for future comers reference I'd like to point that to parse url requests with json one needs to specify that. As it was pointed out to you in this answer.

Community
  • 1
  • 1
Rik Poggi
  • 28,332
  • 6
  • 65
  • 82
  • Thanks. I think I need to get the habit to use `type()` to find out what it returns. – starcorn Mar 27 '12 at 12:19
  • Rik Poggi: it doesn't really say in the documentation that it will return a `dict`, so I guess in most case you have to use `type()` to find out what a function returns in Python? – starcorn Mar 28 '12 at 08:30
  • @starcorn: `json.loads()` wont always return the same object. If you don't know how it's structered the json file (in your case your url request), yes you'll have to use some hack. Otherwise just follow the structure. – Rik Poggi Mar 28 '12 at 09:46
  • For those of you puzzling over wth (heck) to do with `type()`, just do `print type(data)` if `data = json.loads('{"animals": ["cat", "dog"], "4": 4}')` – Amanda Apr 11 '12 at 14:00