Chevron
Chevron

Reputation: 474

Convert HTTPResponse object to dictionary

I'm trying to turn this object into something I can work with in my program. I need to store the message-id to a database. Short of flat-out parsing it, can I just turn this whole thing into a dictionary somehow?

Here is where I'm at with some IDLE testing:

>>> response = urllib.request.urlopen(req)
>>> response.getheaders()
[('Server', 'nginx/1.6.0'), ('Date', 'Sat, 07 Jun 2014 00:32:45 GMT'), ('Content-Type', 'application/json;charset=ISO-8859-1'), ('Transfer-Encoding', 'chunked'), ('Connection', 'close'), ('Cache-Control', 'max-age=1')]
>>> response.read()
b'{"message-count":"1","messages":[{"to":"11234567890","message-id":"02000000300D8F21","status":"0","remaining-balance":"1.82720000","message-price":"0.00620000","network":"302220"}]}'

After a half hour of sifting through google I was able to turn it into a string with:

>>> response.response.decode('utf-8')
>>> print(response)
'{"message-count":"1","messages":[{"to":"11234567890","message-id":"02000000300D8F21","status":"0","remaining-balance":"1.82720000","message-price":"0.00620000","network":"302220"}]}'
>>> type(response)
<class 'str'>

I found this post but here is what I get:

>>> a_dict = dict([response.strip('{}').split(":"),])
Traceback (most recent call last):
File "<pyshell#79>", line 1, in <module>
  a_dict = dict([response.strip('{}').split(":"),])
ValueError: dictionary update sequence element #0 has length 9; 2 is required

Maybe I'm going about this all wrong. What's the quickest way to turn this object into a dictionary or something else I can easily work with?

Upvotes: 4

Views: 16143

Answers (1)

alecxe
alecxe

Reputation: 474141

Load it via json.load():

import json
response = urllib.request.urlopen(req)
result = json.loads(response.readall().decode('utf-8'))
message_id = result['messages'][0]['message-id']

Upvotes: 6

Related Questions