JSON parsing from an API and do something with it

From Media Design: Networked & Lens-Based wiki
Jump to navigation Jump to search

DooFi Skull.svg Unfortunately the example shown on this page no longer works as Twitter has deprecated their REST api. TwitterRESTAPIv1Deactivated.png

Using the Twitter API as an example. More particularly, we are fetching the most recent tweets containing the #cheese hashtag. See the API doc for more information.

Note: JSONView for firefox and chrome allows json search results to be viewed in the browser

import urllib2, json

url = 'http://search.twitter.com/search.json?q=%23cheese'
f = urllib2.urlopen(url)
data = json.load(f)

for r in data['results']:
    print r['from_user'] + ' says "' + r['text'] + '"'


This is another script that displays tweets. We're going to chmod it (and add a shebang) so that we can use the script more easily.
Chmod it by removing extension and type in the terminal: chmod +x filename
For easy accessibility, you can put it in your username/bin folder.

Execute this script by typing in the terminal:
filename searchquery
(for example: "JSONtwitter cheese")

#!/usr/bin/python

import sys, json, urllib2, os
 

f = urllib2.urlopen("http://search.twitter.com/search.json?q="+sys.argv[1])
data = json.load(f)

for r in data ["results"]:
	print r["text"]



Exact same story as above, but now espeak read the tweets out aloud:

#!/usr/bin/python

import sys, json, urllib2, os
 

f = urllib2.urlopen("http://search.twitter.com/search.json?q="+sys.argv[1])
data = json.load(f)

os.system("espeak cool")
for r in data ["results"]:
	print r["text"]
	os.system('espeak "'+r["text"].encode("utf-8") + '"')


wikipedia api query example (in json): http://en.wikipedia.org/w/api.php?format=json&action=query&titles=Main%20Page&prop=revisions&rvprop=content

archive.org api query example (json): http://www.archive.org/advancedsearch.php?q=cooking+AND+mediatype:Audio&rows=15&output=json