2013-05-18 49 views
0
import httplib2 
h = httplib2.Http(".cache") 
resp, content = h.request("http://example.org/", "GET") 

當我按照urllib2中的示例向API發出GET請求時,如何反序列化返回對象?Httplib2:處理響應字符串

舉例來說,我可能有類似

'{"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包裝的情況下解析響應?

回答

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)