My request is of type QueryDict and I want to convert it to a JSON object or string so I can validate it against a JSON schema. One of the JSON fields contains a list, like so:
{
"message": "Hello!",
"people": ["Aaron", "Randy", "Chris", "Andrew"]
}
When I convert it to a string using json.dumps(), get the following:
'{"message": "Hello!", "people": "Andrew"}'
What is the best way to go about dealing with this situation?
Convert your QueryDict
into a standard Python dict
and call json.dumps()
on the resulting dict
:
import json
from django.http import QueryDict
qd = QueryDict('people=Aaron&people=Randy&people=Chris&people=Andrew&message=Hello!')
>>> qd
<QueryDict: {u'message': [u'Hello!'], u'people': [u'Aaron', u'Randy', u'Chris', u'Andrew']}>
>>> json.dumps(qd)
'{"message": "Hello!", "people": "Andrew"}'
>>> json.dumps(dict(qd))
'{"message": ["Hello!"], "people": ["Aaron", "Randy", "Chris", "Andrew"]}'
If you don't like keys with a single value being represented as lists, you can do this:
>>> d = {k:v if len(v) > 1 else v[0] for k,v in qd.iterlists()}
>>> json.dumps(d)
'{"message": "Hello!", "people": ["Aaron", "Randy", "Chris", "Andrew"]}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With