Convert QueryDict into list of arguments
<p>I'm receiving via POST request the next payload through the view below:</p>

<pre><code>class CustomView(APIView):

"""
POST data
"""
def post(self, request):                
    extr= externalAPI()
    return Response(extr.addData(request.data))
</code></pre>

<p>And in the <code>externalAPI</code> class I have the <code>addData()</code> function where I want to convert <em>QueryDict</em> to a simple list of arguments:</p>

<pre><code>def addData(self, params):        
    return self.addToOtherPlace(**params)   
</code></pre>

<p>In other words, what I get in params is somethin like:</p>

<pre><code>&lt;QueryDict: {u'data': [u'{"object":"a","reg":"1"}'], u'record': [u'DAFASDH']}&gt;
</code></pre>

<p>And I need to pass it to the addToOtherPlace() function like:</p>

<pre><code>addToOtherPlace(data={'object':'a', 'reg': 1}, record='DAFASDH')
</code></pre>

<p>I have tried with different approaches but I have to say I'm not very familiar with dictionaries in python.</p>

<p>Any help would be really appreciated.</p>

<p>Thanks!</p>

<p>You can write a helper function that walks through the <em>QueryDict</em> object and converts valid <em>JSON</em> objects to Python objects, string objects that are digits to integers and returns the first item of lists from lists:</p>

<pre><code>import json

def restruct(d):
    for k in d:
        # convert value if it's valid json
        if isinstance(d[k], list):
            v = d[k]
            try:
                d[k] = json.loads(v[0])
            except ValueError:
                d[k] = v[0]

        # step into dictionary objects to convert string digits to integer
        if isinstance(d[k], dict):
            restruct(d[k])
        elif d[k].isdigit():
            d[k] = int(d[k])


params = {u'data': [u'{"object":"a","reg":"1"}'], u'record': [u'DAFASDH']}
restruct(params)
print(params)
# {'record': 'DAFASDH', 'data': {'object': 'a', 'reg': 1}}
</code></pre>

<p>Note that this approach modifies the initial object <em>in-place</em>. You can make a <code>deepcopy</code>, and modify the copy instead if you're going to keep the original object intact:</p>

<pre><code>import copy

def addData(self, params):
    params_copy =  copy.deepcopy(params)  
    restruct(params_copy)   
    return self.addToOtherPlace(**params_copy) 
</code></pre>

python json django dictionary