[Fixed]-Convert QueryDict into list of arguments

1👍

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

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}}

Note that this approach modifies the initial object in-place. You can make a deepcopy, and modify the copy instead if you’re going to keep the original object intact:

import copy

def addData(self, params):
    params_copy =  copy.deepcopy(params)  
    restruct(params_copy)   
    return self.addToOtherPlace(**params_copy) 

Leave a comment