Reputation: 19
I'm trying to efficiently (quickly) convert a byte file into a dictionary. So far I've decoded it to str, stripped the { } and made that into a dictionary. But I still get the single string quotes ' so I cannot call the dict by keys. How do I do this?
response = b'{"address":"[email protected]","username":"david","domain":"gmail.com","md5Hash":"f3c52e5ef3d2b471d0ef51c66c21d10c","suggestion":"","validFormat":true,"deliverable":false,"fullInbox":false,"hostExists":true,"catchAll":false,"gravatar":false,"role":false,"disposable":false,"free":true}'
Steps I took so far:
print(response.decode("utf-8"))
{"address":"[email protected]","username":"david","domain":"gmail.com","md5Hash":"f3c52e5ef3d2b471d0ef51c66c21d10c","suggestion":"","validFormat":true,"deliverable":false,"fullInbox":false,"hostExists":true,"catchAll":false,"gravatar":false,"role":false,"disposable":false,"free":true}
print({response.decode("utf-8").replace("}","").replace("{","")})
{'"address":"[email protected]","username":"david","domain":"gmail.com","md5Hash":"f3c52e5ef3d2b471d0ef51c66c21d10c","suggestion":"","validFormat":true,"deliverable":false,"fullInbox":false,"hostExists":true,"catchAll":false,"gravatar":false,"role":false,"disposable":false,"free":true'}
But I still cannot call the dict by keys due to the '
.
I Need this to be quick, low on resources.
Upvotes: 1
Views: 1416
Reputation: 1078
Like @juanpa.arrivillaga said just use the json
module.
Here:
import json
d = json.loads(response)
Now the value of d
is your decoded dict.
Again like @juanpa.arrivillaga said there is no need to use .decode()
, json.loads()
can operate on bytes.
Upvotes: 2