Search code examples
pythonjsonhttplib

Python httplib retrieve json object from getresponse()


So I currently working on a POST request to an api.

conn = httplib.HTTPSConnection('api.syncano.io')
conn.request(method="POST", url=url, body=postdata, headers=headers)
resp = conn.getresponse()

I used resp.read() but it returns me a string. Are there any way for me to read the response as a JSON object where I could get the result simply by doing resp['result']?


Solution

  • Given that the response body is valid JSON

    import json
    
    respBody = resp.read()
    
    responseObject = json.loads(respBody)
    

    Will create a python dictionary: "responseObject" from the JSON response body.

    More detail: json parsing with python