2

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数据做到这一点的方式上获得帮助......谢谢。

4

2 回答 2

4

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

该解决方案取自此处,用于将原始 json 数据添加到状态对象,并在此处作为骨架代码使用 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 槽。

于 2013-07-30T19:49:31.063 回答
1

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

import json
json_data = json.dumps(data)
于 2013-04-23T21:35:56.393 回答