【问题标题】:Reading Json in python (Django)在 python (Django) 中读取 Json
【发布时间】:2014-08-14 21:56:30
【问题描述】:

我正在为我的 web 应用程序使用 Django。我正在向我的视图发送 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'])

decoded_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={"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}]} 运行您的代码,并且没有错误
  • 是的,当我执行此操作时它可以工作,但是当我从 POST.get("data") 获取它时它不起作用。 request.POST 看起来像这样:
  • 真的在 ' 和 " 之间变化吗?你是怎么打印出来的?print data?
  • 试试这个myDict = dict(data.iterlists()) 看看会发生什么(好像你有一个QueryDict stackoverflow.com/questions/13349573/…
  • 我想你的意思是decoded_data = json.loads(json_encoded[0])我做到了,它说Expecting value: line 1 column 1 (char 0)

标签: javascript python json django


【解决方案1】:

改成:

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

request.POST.get("data") 是一个字符串。只需从那里加载它。

【讨论】:

  • 它说解码错误
【解决方案2】:

'NoneType' 是 None 的类型(相当于 python 中的 Null),只有在变量设置不正确或设置为 my_variable = None 时才会出现。

如果数据是一个等于这个的字符串:

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

【讨论】:

    【解决方案3】:

    我发现了问题!我在我的“/” url 中使用了这段代码,而这段代码第一次被调用的数据是 Null,所以我必须检查调用是否是 AJAX 并在这种情况下使用这段代码。

    【讨论】:

      猜你喜欢
      • 2012-09-20
      • 1970-01-01
      • 1970-01-01
      • 2018-11-02
      • 2019-07-15
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多