Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode JSON with Python [duplicate]

Tags:

python

json

I'm getting my JSON from reddit.com, essentially something like this. I have done quite a bit of reading, but I don't really understand how I can grab the information I want from this JSON (I want a list of the story links). I understand that I can "decode" the JSON into a dictionary, but do I need to recur throughout the JSON to get what I need?

Thanks in advance.

like image 289
awegawef Avatar asked Feb 25 '10 05:02

awegawef


People also ask

Can JSON have duplicate keys Python?

python - json. loads allows duplicate keys in a dictionary, overwriting the first value - Stack Overflow.

Can JSON have duplicate fields?

The JSON standard recommends that a JSON object not have duplicate field names.

Can JSON have multiple keys with same name?

There is no "error" if you use more than one key with the same name, but in JSON, the last key with the same name is the one that is going to be used. In your case, the key "name" would be better to contain an array as it's value, instead of having a number of keys "name".


2 Answers

If you're using Python 2.6 or later, use the built-in json library. Otherwise, use simplejson which has exactly the same interface.

You can do this adaptively without having to check the Python version yourself, using code such as the following:

try:
    import json
except ImportError:
    import simplejson as json

Then, use json.loads() or whatever as appropriate.

like image 154
Greg Hewgill Avatar answered Sep 30 '22 02:09

Greg Hewgill


import urllib2
import json

u = urllib2.urlopen('http://www.reddit.com/.json')
print json.load(u)
u.close()
like image 43
Ignacio Vazquez-Abrams Avatar answered Sep 30 '22 02:09

Ignacio Vazquez-Abrams