Frage

import httplib2
h = httplib2.Http(".cache")
resp, content = h.request("http://example.org/", "GET")

When I follow the examples in urllib2 to make a GET request to an API, how do I deserialize the return object?

For instance, I may have something like

'{"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"}}}'

However, the response above is a string. Is there anyway to convert it to an list for easier querying? Is this the correct idea behind making API calls (new to this) : to send a request with a HTTP API then parse the response assuming no API wrapper exists?

War es hilfreich?

Lösung

Use 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'}}}

As for if it's a correct way: sure. If it works, then why not? Personally, I'd use the requests module:

>>> import requests
>>> resp = requests.get(URL)
>>> mydict = json.loads(resp.content)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top