Skip to content Skip to sidebar Skip to footer

Decoding JSON From Reddit API In Python Using PRAW

I am using PRAW for Reddit API in a Python/GTK application. I have been successful in using the API, but I can't seem to be able to decode the JSON for use. It should be known tha

Solution 1:

With PRAW you do not need to do any json decoding as PRAW handles all of that for you.

Say for example for each submission you want to print out the number of upvotes, the number of downvotes, and the submission title. You could do:

for submission in r.get_front_page(limit=5):
    print submission.ups, submission.downs, submission.title

If you want to see all the attributes available to use on a submission object you can run:

import pprint
for submission in r.get_front_page(limit=5):
    pprint.pprint(vars(submission))

Additionally if you want to get the comments from a submission then you can use the submission.comments property. You can also manually look at the json response for a request to see what attributes should be available through PRAW (example).

The attributes are not explicitly listed anywhere for the objects because the attributes are created directly from whatever the key name is in the associated json response for the request.


Solution 2:

JSON is simply a dictionary of dictionaries, extended with lists, if needed.

A good way to get familiar with whatever JSON you're dealing with at the moment is to load it, and play around with it by accessing the dictionary elements in a more straightforward way.

>>> import urllib2
>>> import json
>>> response = urllib2.urlopen('http://reddit.com/user/droogans.json').read()
>>> js = json.loads(response)
>>> comment = js['data']['children'][0]['data']
>>> #this is my most recent comment, along with a lot of other interesting stuff
>>> print comment['ups']
9001

So, explore the data, and you'll understand it better.


Post a Comment for "Decoding JSON From Reddit API In Python Using PRAW"