Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QueryDict to string loses list within JSON

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?

like image 425
farbodg Avatar asked Feb 20 '15 04:02

farbodg


1 Answers

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"]}'
like image 88
mhawke Avatar answered Nov 20 '22 20:11

mhawke