JSON parsing from an API and do something with it: Difference between revisions
No edit summary |
Andrecastro (talk | contribs) No edit summary |
||
Line 1: | Line 1: | ||
Using the Twitter API as an example. More particularly, we are fetching the most recent tweets containing the #cheese hashtag. See the [http://apiwiki.twitter.com|Twitter API doc] for more information. | Using the Twitter API as an example. More particularly, we are fetching the most recent tweets containing the #cheese hashtag. See the [http://apiwiki.twitter.com|Twitter API doc] for more information. | ||
Note: JSONView for firefox and chrome allows json search results to be viewed in the browser | |||
<source lang="python"> | <source lang="python"> |
Revision as of 13:30, 9 February 2012
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") + '"')