[英]Reading Json in python (Django)
我正在使用Django作為我的webapp。 我正在向我的視圖發送JSON數據但是我無法通過調用decoded_data['nodes']
來訪問節點和邊緣,它給了我:
'NoneType' object is not subscriptable
錯誤信息。
以下是我將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}
});
這是我的看法:
data = request.POST.get("data")
json_encoded = json.dumps(data)
decoded_data = json.loads(json_encoded)
logger.error(decoded_data['nodes'])
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}]}
我感謝您的幫助
將其更改為:
data = request.POST.get("data")
try:
decoded_data = json.loads(data)
nodes = decoded_data.get("nodes")
except:
print("ERROR decoding")
request.POST.get(“data”)是一個字符串。 只需從那里加載它。
'NoneType'是None
的類型(在python中等效於Null),並且只應在未正確設置變量或者設置為my_variable = None
。
如果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 }]}'
然后只需使用以下代碼即可:
decoded_data = json.loads(data)
檢查您的請求是否真的來自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"]
我發現了問題! 我在我的“/”url中使用此代碼,並且第一次調用此代碼時數據為Null,因此我必須檢查調用是否為AJAX並在此條件下使用此代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.