【发布时间】:2014-07-23 01:02:21
【问题描述】:
我希望使用 Tweepy 作为 JSON 从 Twitter 获取搜索结果。 我看到here 说我应该在 Tweepy 代码中添加一个类来使这个功能起作用。
但是当我查看 Tweepy 代码时,我得到了这样的结果:
class JSONParser(Parser):
payload_format = 'json'
def __init__(self):
self.json_lib = import_simplejson()
def parse(self, method, payload):
try:
json = self.json_lib.loads(payload)
except Exception, e:
raise TweepError('Failed to parse JSON payload: %s' % e)
needsCursors = method.parameters.has_key('cursor')
if needsCursors and isinstance(json, dict) and 'previous_cursor' in json and 'next_cursor' in json:
cursors = json['previous_cursor'], json['next_cursor']
return json, cursors
else:
return json
def parse_error(self, payload):
error = self.json_lib.loads(payload)
if error.has_key('error'):
return error['error']
else:
return error['errors']
所以我没有义务破解它的代码,因为这个功能已经存在。
这就是我的代码的样子:
from tweepy.parsers import JSONParser
for tweet in tweepy.Cursor(api.search,
q=hashtag,
include_entities=True,
rpp=100,
parser=tweepy.parsers.JSONParser()
).items(limit):
这是我得到的错误:
print (json.dumps(tweet))
File "/usr/lib/python2.7/json/__init__.py", line 243, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <tweepy.models.Status object at 0xb6df2fcc> is not JSON serializable
我应该从这个错误中理解什么?我该如何解决?
【问题讨论】:
-
可以在answer 中找到更好(更简单)的方法来解决类似的问题
标签: python json twitter tweepy