【问题标题】:StremListener does't return data in JSON in tweepyStremListener 不会在 tweepy 中以 JSON 格式返回数据
【发布时间】:2013-04-17 06:29:54
【问题描述】:

我的目标是从def on_status(self, status): 以json 格式获取数据。 现在我以类似于 JSON 的形式返回数据,但它不是 JSON:

{'favorited': False, 'contributors': None, 'truncated': False, 'text': 'Lol. As long as you and Tsidi are awake, am not sleeping RT @TboyMP: @Fufu_Tinkies hambo lala wena!! LMAO!!', 'source_url': 'http://ubersocial.com', 'in_reply_to_status_id': None, 'user': <tweepy.models.User object at 0x1b4f3d0>, 'filter_level': 'medium', 'geo': None, 'id': 326808604013379586, 'favorite_count': 0, 'source': 'UberSocial for BlackBerry', 'lang': 'en', 'author': <tweepy.models.User object at 0x1b4f3d0>, 'created_at': datetime.datetime(2013, 4, 23, 21, 23, 37), 'retweeted': False, 'coordinates': None, 'in_reply_to_user_id_str': None, 'entities': {'symbols': [], 'user_mentions': [{'id': 282499717, 'indices': [60, 67], 'id_str': '282499717', 'screen_name': 'TboyMP', 'name': 'Thulane Khanye'}, {'id': 157961325, 'indices': [69, 82], 'id_str': '157961325', 'screen_name': 'Fufu_Tinkies', 'name': 'Nomfundo'}], 'hashtags': [], 'urls': []}, 'in_reply_to_status_id_str': None, 'in_reply_to_screen_name': None, 'id_str': '326808604013379586', 'place': None, 'retweet_count': 0, 'in_reply_to_user_id': None}

如您所见,它使用单引号而不是双引号。我得到这个的方式是:

data = status.__getstate__()

但是我不能 load 使用 json 模块:它给了我一个错误:

Encountered Exception: expected string or buffer

那么如何从 JSON 中删除数据或将其转换为 JSON?

更新

我想要这样的东西:

>>> data = '[{"fooo":"bar","something":"another bar"}]'
>>> ww = json.loads(data)
>>> ww[0]['fooo']
u'bar'

我希望通过tweepy 数据获得帮助...... 谢谢。

【问题讨论】:

    标签: python json tweepy


    【解决方案1】:

    这会将 def on_status(self, status): 中的原始 json 数据写入文件。

    此解决方案取自 here,用于将原始 json 数据添加到状态对象,并将 here 作为骨架代码以使用 tweepy 的流式传输功能。

    @classmethod                    
    def parse(cls, api, raw):
            status = cls.first_parse(api, raw)
            setattr(status, 'json', json.dumps(raw))
            return status
    
    tweepy.models.Status.first_parse = tweepy.models.Status.parse
    tweepy.models.Status.parse = parse
    
    _dir = os.path.dirname(os.path.abspath(__file__))
    
    class CustomStreamListener(tweepy.StreamListener):
        def on_status(self, status):
            print status.user.screen_name
            with codecs.open(os.path.join(_dir, 'tweets.json'), "a", 'utf-8') as textFile:
                    textFile.write(status.json)
                    textFile.write('\n')
    
        def on_error(self, status_code):
            print >> sys.stderr, 'Encountered error with status code:', status_code
            return True # Don't kill the stream
    
        def on_timeout(self):
            print >> sys.stderr, 'Timeout...'
            return True # Don't kill the stream
    

    我不是 Python 专家,但似乎正在使用新版本对 parse 方法进行热修补,然后将新版本安装到 tweepy 类层次结构中。新版本调用旧版本,然后在原parse方法返回的对象上追加一个json槽。

    【讨论】:

      【解决方案2】:

      你有一个 Python 字典,将它转换为 JSON 使用 json.dumps():

      import json
      json_data = json.dumps(data)
      

      【讨论】:

      • 您在问题中打印的结构是 Python 字典,这与 json.loads() 将返回的内容相同。您应该能够以您想要的方式使用您已经拥有的任何东西,例如data['favorited'],而无需担心任何 JSON 转换。
      • 如果我这样做:data = things that I paste 我会得到SyntaxError: invalid syntax
      • 这行得通,只是它似乎不是递归的,因此它不会深入到用户对象的“用户”键并获取它的所有属性。相反,我收到此错误:TypeError: &lt;tweepy.models.User object at 0x10137a850&gt; is not JSON serializable
      • @ClaytonStanley 听起来您的问题有点不同,我建议您提出一个新问题。
      猜你喜欢
      • 2011-06-11
      • 2015-06-26
      • 2017-02-24
      • 2019-08-11
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      相关资源
      最近更新 更多