JSON parsing from an API and do something with it: Difference between revisions
No edit summary |
No edit summary |
||
Line 12: | Line 12: | ||
</source> | </source> | ||
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.<br> | |||
Chmod it by removing extension and type in the terminal: chmod +x filename<br> | |||
For easy accessibility, you can put it in your username/bin folder.<br> | |||
Execute this script by typing in the terminal:<br> | |||
filename searchquery<br> | |||
(for example: "JSONtwitter cheese") | |||
<source lang="python"> | |||
#!/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"] | |||
</source> | |||
Exact same story as above, but now espeak read the tweets out aloud: | |||
<source lang="python"> | |||
#!/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") + '"') | |||
</source> | |||
[[Category:Cookbook]] | [[Category:Cookbook]] |
Revision as of 15:16, 21 January 2011
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.
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") + '"')