7

I'm trying to get Twitter API search results for a given hashtag using Python, but I'm having trouble with this "No JSON object could be decoded" error. I had to add the extra % towards the end of the URL to prevent a string formatting error. Could this JSON error be related to the extra %, or is it caused by something else? Any suggestions would be much appreciated.

A snippet:

import simplejson
import urllib2

def search_twitter(quoted_search_term): 
    url = "http://search.twitter.com/search.json?callback=twitterSearch&q=%%23%s" % quoted_search_term
    f = urllib2.urlopen(url)
    json = simplejson.load(f)
    return json
user374372
  • 190
  • 2
  • 4
  • 14
  • 1
    What is the actual content of the response? Using your code, you can find that with something like `content = f.read()`. – Will McCutchen Jul 30 '10 at 14:59
  • I used your code and tried printing content but got the same error: JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0) function pull_tweets in twitter_puller_1.py at line 28 data1 = search_twitter(query1) function search_twitter in twitter_puller_1.py at line 14 json = simplejson.load(f) function load in untitled at line 328 None function loads in untitled at line 384 None function decode in untitled at line 402 obj, end = self.raw_decode(s, idx=_w(s, 0).end()) function raw_decode in untitled at line 420 raise JSONDecodeError("No JSON object could be decoded", s, idx) – user374372 Jul 30 '10 at 15:26
  • 1
    See blcArmadillo's answer. You need to remove the `callback` argument from your request to Twitter. Something like `url = "http://search.twitter.com/search.json?q=%s" % quoted_search_term` should work. – Will McCutchen Jul 30 '10 at 17:02

1 Answers1

8

There were a couple problems with your initial code. First you never read in the content from twitter, just opened the url. Second in the url you set a callback (twitterSearch). What a call back does is wrap the returned json in a function call so in this case it would have been twitterSearch(). This is useful if you want a special function to handle the returned results.

import simplejson
import urllib2

def search_twitter(quoted_search_term): 
    url = "http://search.twitter.com/search.json?&q=%%23%s" % quoted_search_term
    f = urllib2.urlopen(url)
    content = f.read()
    json = simplejson.loads(content)
    return json
Ian Burris
  • 6,325
  • 21
  • 59
  • 80
  • 3
    You're half right. The actual problem was the `callback` argument, which causes Twitter to return `JSONP`, which can't be parsed as JSON`. But the code for reading the JSON was fine (it just passed the file-like object `f` directly to the `simplejson.load()` function, which takes file-like objects). – Will McCutchen Jul 30 '10 at 17:00
  • Thank you so much for explaining this to me, blcArmadillo and Will McCutchen! It works now :) – user374372 Aug 02 '10 at 13:00