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

urllib2의 예제를 따라 API에 GET 요청을하면 반환 개체를 deserialize하는 방법은 무엇입니까?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)