Jquery – Reading multidimensional arrays from a POST request in Django

djangojquerypost

I have a jquery client that is sending a POST request with a multidimensional array, something like this:

friends[0][id]    12345678 
friends[0][name]  Mr A
friends[1][id]    78901234
friends[1][name]  Mr B

That is, an array of two items, name and id.

Is there an automatic way to receive this input as list or a dictionary? I can't seem to be able to make .getlist work

Best Solution

DrMeers' link is no longer valid, so I'll post another method of achieving the same thing. It's also not perfect, and it would be much better if Django had such a function built-in. But, since it doesn't:

Converting Multi-dimensional Form Arrays in Django

Disclaimer: I wrote that post. The essence of it is in this function, which could be more robust, but it works for arrays of one-level objects:

    def getDictArray(post, name):
        dic = {}
        for k in post.keys():
            if k.startswith(name):
                rest = k[len(name):]
                
                # split the string into different components
                parts = [p[:-1] for p in rest.split('[')][1:]
                print parts
                id = int(parts[0])
                
                # add a new dictionary if it doesn't exist yet
                if id not in dic:
                    dic[id] = {}
                    
                # add the information to the dictionary
                dic[id][parts[1]] = post.get(k)
        return dic