【问题标题】:error loading json using topsy使用 topsy 加载 json 时出错
【发布时间】:2015-03-08 13:12:09
【问题描述】:

当我加载单个记录时,当我尝试加载多个记录时,创建的 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)

【问题讨论】:

  • 您也可以发布您生成的 JSON 吗? JSON 解析器失败了,所以看起来你的 JSON 格式不正确。
  • 我应该发布一个 pastebin 吗?因为我觉得在这里发布似乎很长时间
  • 如果您认为它太长了,您可以发布一个总结示例(失败的最短用例)或一个 Pastbin 链接(不太受欢迎)。
  • 我已经添加了json响应tny.cz/ce1baaba的链接
  • 您生成的JSON 不是分层的,您有两个对象{...} 并排。它们需要包装在某种外部结构中才能有效JSON(比如和数组[...]

标签: json python-2.7 twitter topsy


【解决方案1】:

感谢 Timusan,我能够更正我的 json 原始文件的问题是它缺少根元素“[”,这表明我们正在期待数组,并且每个对象结束后都缺少“,”。所以这里是固定代码。 所以这里是代码

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)

【讨论】:

  • 是的,它解决了问题,记住它只会解决api.topsy.com/v2/content/bulktweets.json的json返回。
  • 很高兴听到这个消息。但是为了让您自己的答案对可能偶然发现它的其他人更有用:更清楚地说明为什么会这样。多解释一下你做了什么(自从不工作的例子发生了什么变化)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-29
相关资源
最近更新 更多