Hirad Roshandel
Hirad Roshandel

Reputation: 2187

Reading Json in python (Django)

I'm using Django for my 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 :

'NoneType' object is not subscriptable

error message.

Here is how I send json to to my view:

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:

{"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

Upvotes: 1

Views: 195

Answers (3)

t.pimentel
t.pimentel

Reputation: 1575

'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.

If data is a string equal to this:

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:

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"]

Upvotes: 1

Hirad Roshandel
Hirad Roshandel

Reputation: 2187

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.

Upvotes: 0

tom.alexander
tom.alexander

Reputation: 219

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. Just load it from there.

Upvotes: 2

Related Questions