farbodg
farbodg

Reputation: 705

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?

Upvotes: 5

Views: 6287

Answers (2)

Zhimin
Zhimin

Reputation: 1

this way can handle loss case:

dq_dict = {k:v if len(v) > 1 else v[0] for k,v in qd.lists()}

Upvotes: 0

mhawke
mhawke

Reputation: 87134

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"]}'

Upvotes: 12

Related Questions