简体   繁体   English

如何在python中从JSON对象获取数据数组?

[英]How get data array from JSON object in python?

I have a jquery POST function like this : 我有一个像这样的jquery POST函数:

 $.post(data_send_url,
    {
        all_letters:["A","B","C"]
    },
    function(data, status){
        alert(data);
});

In the server side when I access it using request.data in a Django view function I get <QueryDict: {'all_letters[]': ['e', 'r', 'p']}> . 在服务器端,当我使用Django view function request.data访问它时,我得到<QueryDict: {'all_letters[]': ['e', 'r', 'p']}> How can I get a Python list like all_letters = ['e','r','p'] ? 如何获得像all_letters = ['e','r','p']这样的Python列表?

This code solved my problem: 这段代码解决了我的问题:

$.post(data_send_url,
    {
        all_letters:JSON.stringify(["A","B","C"]), //JSON.stringify added
    },
    function(data, status){
        alert(data);
});

And in views.py 在views.py中

json.loads(request.data.get("all_letters"))
json.loads(request.POST["all_letters"]) #both of these work fine

can you try to stringify the array and after this use json.loads ? 你可以尝试对array进行stringify ,然后使用json.loads吗?

$.post(data_send_url,
    {
        all_letters: JSON.stringify(["A","B","C"])
    },
    function(data, status){
        alert(data);
});

# and after this use json.loads
import json

print(json.loads(request.data['all_letters']))

Try 'all_letter[]' as key just like below: 尝试'all_letter []'作为关键,如下所示:

request.data["all_letters[]"]

This might work otherwise try to construct querydict properly in JS code and try to access it. 这可能会起作用,否则尝试在JS代码中正确构造querydict并尝试访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM