chris Frisina
chris Frisina

Reputation: 19688

Convert a python bytes to a dict or json, when bytes is not in object notation

How do you convert a bytes type to a dict, when the bytes aren’t in a json/object format?

example
request.body = b'Text=this&Voice=that' to something like

request.body => {'Text' : 'this', 'Voice' : 'that'}

Python 3.5 or 3.6?

Upvotes: 0

Views: 491

Answers (2)

VePe
VePe

Reputation: 1781

Since = and & in names/values should be encoded, you can do something like:

r = b'Text=this&Voice=that'
postdata = dict(s.split(b"=") for s in r.split(b"&"))
print(postdata)

The above should output:

{b'Text': b'this', b'Voice': b'that'}

And in case you want to get rid of the bytes:

r = b'Text=this&Voice=that'
r = r.decode("utf-8") #here you should add your encoding, with utf-8 you are mostly covered for ascii as well
postdata = dict([s.split("=") for s in r.split("&")])
print(postdata)

which should print:

{'Text': 'this', 'Voice': 'that'}

Upvotes: 3

Joshua Fox
Joshua Fox

Reputation: 19675

Use the standard parse_qs:

from urllib.parse import parse_qs 
from typing import List, Dict
s = request.body.decode(request.body, request.charset)
query:Dict[str,List[str]= parse_qs(s)

(It is unusual that this query-string is in the request.body, but if it is, this is how you do it.)

Upvotes: 2

Related Questions