I use this to go from URL params (received as bytes in the body of a HTTP request) to a JSON string:
import urllib.parse, json
def params_asbytes_to_json(b):
s = b.decode() # bytes to str
x = urllib.parse.parse_qsl(s) # parse_qsl
d = dict(x) # convert to dict
return json.dumps(d) # convert to string with json
print(params_asbytes_to_json(b'a=b&c=d')) # {"a": "b", "c": "d"}
It works, but as it involes many encoding/decoding steps, I suspect it to be inefficient (if my server receives many requests).
Is there shorter/faster to go from bytes a=b&c=d
to the JSON string {"a": "b", "c": "d"}
?
PS: this data is sent from a HTML <form>
like this:
<form action='/do' method='post'>
<input type='text' name='a' value='b'>
<input type='submit'>
</form>
and, for other pages, via (Vanilla) Javascript:
var xhr = new XMLHttpRequest();
xhr.open("POST", "/do");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var fd = new FormData(document.querySelector('form'));
fd.append('dt', +new Date());
xhr.send(new URLSearchParams(fd).toString());
PS: I have already read How to send a JSON object using html form data, but I need my website to work even if Javascript is disabled, so I can't 100% rely on XMLHttpRequest + JSON.serialize : it needs to work with just a <form>
submit. As far as I know, a standard HTML form can't post directly as JSON, is that right?