从Django中的POST请求中读取多维数组

Lio*_*ion 11 django jquery post

我有一个jquery客户端发送带有多维数组的POST请求,如下所示:

friends[0][id]    12345678 
friends[0][name]  Mr A
friends[1][id]    78901234
friends[1][name]  Mr B
Run Code Online (Sandbox Code Playgroud)

也就是说,一个包含两个项目的数组,name和id.

是否有自动方式接收此输入作为列表或字典?我似乎无法使.getlist工作

Her*_*aaf 7

DrMeers的链接不再有效,所以我将发布另一种实现相同功能的方法.它也不完美,如果Django内置了这样的功能会好得多.但是,因为它没有:

在Django中转换多维表格数组

免责声明:我写了这篇文章.它的本质是在这个函数中,它可以更健壮,但它适用于一级对象的数组:

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
Run Code Online (Sandbox Code Playgroud)

  • @Liorsion:用"return [item for key,item in sorted(dic.items())]"替换最后一行,你将得到相应的列表作为返回对象. (2认同)

ber*_*rni 5

这与该问题有关.如上所述,我为Django/Python创建了一个特殊的库来处理通过请求发送的多维数组.你可以找到它在GitHub上这里.