سؤال

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.

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top