0
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 ラッパーが存在しないと仮定して応答を解析しますか?

4

1 に答える 1

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)
于 2013-05-18T00:09:25.887 に答える