使用topsy加载json时出错

时间:2015-01-10 07:01:57

标签: json python-2.7 twitter topsy

当我加载单个记录json创建时我尝试加载多个记录就好了我得到了这个错误。对不起,我是python http://tny.cz/ce1baaba

的新手
Traceback (most recent call last):
  File "TweetGraber.py", line 26, in <module>
    get_tweets_by_query(topic)
  File "TweetGraber.py", line 15, in get_tweets_by_query
    json_tree = json.loads(source)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 368, in decode
    raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 2 column 1 - line 11 column 1 (char 2380 - 46974)

这是我的代码

def get_tweets_by_query(query, count=10):
    """A function that gets the tweets by a query."""
    Tweets=[]
    queryEncoded=urllib.quote(query)
    api_key = "xxxxx"
    source=urllib.urlopen("http://api.topsy.com/v2/content/bulktweets.json?q=%s&type=tweet&offset=0&perpage=%s&window=realtime&apikey=%s" % (queryEncoded, count, api_key)).read()
    json_tree = json.loads(source)
    pprint(json_tree)
topic = raw_input("Please enter a topic: ")
get_tweets_by_query(topic)

1 个答案:

答案 0 :(得分:0)

谢谢Timusan我能够纠正我的json问题原来它缺少根元素&#34; [&#34;这表明我们期待阵列和那里&#34;,&#34;在每个对象结束后丢失。所以这是固定代码。 所以这是代码

def get_tweets_by_query(query, count=10):
    """A function that gets the tweets by a query."""
    Tweets=[]
    queryEncoded=urllib.quote(query)
    api_key = "xx"
    source=urllib.urlopen("http://api.topsy.com/v2/content/bulktweets.json?q=%s&type=tweet&offset=0&perpage=%s&window=realtime&apikey=%s" % (queryEncoded, count, api_key)).read()
    source="["+source+"]"
    source=source.replace("}\n{","},{")
    json_tree = json.loads(source)
    pprint(json_tree)