简体   繁体   English

在python中读取Json(Django)

[英]Reading Json in python (Django)

I'm using Django for my webapp. 我正在使用Django作为我的webapp。 I'm sending a JSON data to my views but I'm not able to access Nodes and edges by calling decoded_data['nodes'] and it gives me : 我正在向我的视图发送JSON数据但是我无法通过调用decoded_data['nodes']来访问节点和边缘,它给了我:

'NoneType' object is not subscriptable

error message. 错误信息。

Here is how I send json to to my view: 以下是我将json发送到我的视图的方式:

var a={
            nodes:   thisGraph.nodes,
            edges: saveEdges
        };

    //send data to server
    $(document).ready(function(){
    function change(){
        $.ajax({
        type:"POST",
        url: "/",
        data: {'data': JSON.stringify(a)},
        dataType: "json",  
        success: function(){
        console.log("Ajax worked");
        $('#message').text("Ajax worked");
        },
        headers:{'X-CSRFToken': csrftoken}
    });

here is my view: 这是我的看法:

data = request.POST.get("data")
json_encoded = json.dumps(data) 
decoded_data = json.loads(json_encoded)
logger.error(decoded_data['nodes'])

the decoded_data looks like this: decode_data看起来像这样:

{"nodes":[{"type":"node","title":"new concept","id":0,"x":658,"y":100},{"type":"
constraint","id":2,"title":"new Constraint","x":371,"y":95}],"edges":[{"source":
2,"target":0}]}

I appreciate your help 我感谢您的帮助

Change it to: 将其更改为:

data = request.POST.get("data")
try:
    decoded_data = json.loads(data)
    nodes = decoded_data.get("nodes")
except:
    print("ERROR decoding")

request.POST.get("data") is a string. request.POST.get(“data”)是一个字符串。 Just load it from there. 只需从那里加载它。

'NoneType' is the type of None (Equivalent to Null in python) and should only appear if a variable was not correctly set, or if it was set as my_variable = None . 'NoneType'是None的类型(在python中等效于Null),并且只应在未正确设置变量或者设置为my_variable = None

If data is a string equal to this: 如果data是一个等于这个的字符串:

data = '{"nodes":[{"type":"node","title":"new concept","id":0,"x":658,"y":100},{"type":" node","id":2,"title":"new Node","x":334,"y":60}],"edges":[{"source":2,"target":0 }]}'

Then simply using the following code should work: 然后只需使用以下代码即可:

decoded_data = json.loads(data)

Check if your requests are really coming from the AJAX request or if data == None like this: 检查您的请求是否真的来自AJAX请求,或者data == None这样:

data = request.POST.get("data")
if data === None:
    return "Error: not correctly formed request"
else:
    decoded_data = json.loads(data)
    nodes = decoded_data["nodes"]
    edges = decoded_data["edges"]

I found the problem! 我发现了问题! I was using this code in my "/" url and the first time this code was getting called data was Null so I had to check if the call was AJAX and use this code in that condition. 我在我的“/”url中使用此代码,并且第一次调用此代码时数据为Null,因此我必须检查调用是否为AJAX并在此条件下使用此代码。

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

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