0

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?

2
  • 1
    That looks kind of like it came from an HTML form, but it doesn't quite seem right - a GET wouldn't have that data in the body, and a POST wouldn't usually have the data in that format. Can you give more context? It's likely that the most appropriate option is an established library routine, and that trying to decode it without knowing the context would miss encoding details. Commented Nov 18, 2018 at 7:57
  • I can't control what the POST data coming in comes from/looks like/what format. It is the response from a third party app. Commented Nov 18, 2018 at 8:11

2 Answers 2

3

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'}
Sign up to request clarification or add additional context in comments.

3 Comments

You could also think about a regex
Like the dict-construction step there at the beginning. You don't really need to build a list though: dict(s.split(b"=") for s in r.split(b"&")) works.
@martineau indeed. As a note in the martineau example, instead of passing a list, we pass a generator. I have changed the first example to reflect that. cheers
2

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.)

1 Comment

I think you've got your annotation syntax mixed up. You want Dict[str, List[str]].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.