import httplib2
h = httplib2.Http(".cache")
resp, content = h.request("http://example.org/", "GET")
当我按照urllib2中的示例向API发出GET请求时,如何反序列化返回对象?
例如,我可能有像
这样的东西'{"total_results": 1, "stat": "ok", "default_reviewers": [{"file_regex": ".*", "users": [], "links": {"self": {"href": "http://localhost:8080/api/default-reviewers/1/", "method": "GET"}, "update": {"href": "http://localhost:8080/api/default-reviewers/1/", "method": "PUT"}, "delete": {"href": "http://localhost:8080/api/default-reviewers/1/", "method": "DELETE"}}, "repositories": [], "groups": [], "id": 1, "name": "Default Reviewer"}], "links": {"self": {"href": "http://localhost:8080/api/default-reviewers/", "method": "GET"}, "create": {"href": "http://localhost:8080/api/default-reviewers/", "method": "POST"}}}'
但是,上面的响应是一个字符串。无论如何将其转换为列表以便于查询?这是启动API调用背后的正确理念(对此新增):使用HTTP API发送请求然后解析响应,假设不存在API包装器?
答案 0 :(得分:1)
使用json.loads()
:
>>> import json
>>> mydict = json.loads(content)
>>> print mydict
{u'total_results': 1, u'stat': u'ok', u'default_reviewers': [{u'file_regex': u'.*', u'users': [], u'links': {u'self': {u'href': u'http://localhost:8080/api/default-reviewers/1/', u'method': u'GET'}, u'update': {u'href': u'http://localhost:8080/api/default-reviewers/1/', u'method': u'PUT'}, u'delete': {u'href': u'http://localhost:8080/api/default-reviewers/1/', u'method': u'DELETE'}}, u'repositories': [], u'groups': [], u'id': 1, u'name': u'Default Reviewer'}], u'links': {u'self': {u'href': u'http://localhost:8080/api/default-reviewers/', u'method': u'GET'}, u'create': {u'href': u'http://localhost:8080/api/default-reviewers/', u'method': u'POST'}}}
至于它是否是正确的方法:当然。如果它有效,那为什么不呢?就个人而言,我使用requests
模块:
>>> import requests
>>> resp = requests.get(URL)
>>> mydict = json.loads(resp.content)