Created
April 22, 2011 20:53
-
-
Save j2labs/937610 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| from tweepy.models import Model, User | |
| import urllib | |
| import json | |
| import copy | |
| general_function_map = { | |
| 'created_at': lambda dt: '%s' % dt.strftime('%x'), | |
| 'user': lambda u: unparse_user(u), | |
| 'status': lambda s: unparse_status(s), | |
| } | |
| def unparse_user(model): | |
| del_keys = ['_api'] | |
| return _unparse_model(model, general_function_map, del_keys) | |
| def unparse_status(model): | |
| del_keys = ['_api'] | |
| return _unparse_model(model, general_function_map, del_keys) | |
| def _unparse_model(model, function_map=None, del_keys=None): | |
| md = copy.copy(model.__dict__) | |
| fields = md.keys() ## won't return vars that start with __ | |
| # convert fields as `function_map` specifies | |
| data_dict = dict() | |
| for field in fields: | |
| value = md[field] | |
| if field in del_keys: | |
| continue | |
| if field in function_map: | |
| fun = function_map[field] | |
| value = fun(value) | |
| data_dict[field] = value | |
| # return structure safe for json.dumps | |
| return data_dict | |
| if __name__ == "__main__": | |
| user_url = 'http://api.twitter.com/1/users/show.json?screen_name=j2labs' | |
| json_data = urllib.urlopen(user_url).read() | |
| data = json.loads(json_data) | |
| # from twitter to tweepy | |
| u = User.parse(None, data) | |
| # from tweepy to json | |
| print json.dumps(unparse_user(u)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment