繁体   English   中英

StremListener在tweepy中不会以JSON返回数据

[英]StremListener does't return data in JSON in tweepy

我的目标是从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__()

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

Encountered Exception: expected string or buffer

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

UPDATE

我想要这样的东西:

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

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

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

此解决方案来自此处 ,将原始json数据添加到status对象, 此处为使用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槽。

您拥有的是Python字典,可使用json.dumps()将其转换为JSON:

import json
json_data = json.dumps(data)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM