Jotting this down for fellow googlers. I recently started learning a bit of python and wrote a small script to fetch the latest tweet. When you are new to a programming language, it takes time to grasp some errors. If you see this error while parsing json using python and simplejson, the problem possibly is that, the json is actually encosed in a list [ ]
. If you look carefully, you’ll see your json data (pyton dictionary datatype) is actually enclosed in a python list datatype. The following code will reproduce the error.
#!/usr/bin/python import urllib2 import simplejson as json import os import re url = 'http://twitter.com/statuses/user_timeline/free_thinker.json?count=1' tweetdata = json.loads(urllib2.urlopen(url).read()) print tweetdata print tweetdata['text']
If you execute the above code, you’ll see the json dump and thereafter the error.
To correct the error, change the print tweetdata['text']
to print tweetdata[0]['text']
.
How does this work? Well the dictionary is enclosed inside the list and is first and only element in the list, hence the 0th element.
Hope this helps.
after 2 hours and tons of useless stackflow answers, your article did the trick!
so many thanks!
Thanks sir. This helped a bit. It printed the first one. Now to print the others.