【问题标题】:can't access json object from python method无法从 python 方法访问 json 对象
【发布时间】:2014-07-16 16:11:02
【问题描述】:

我查看了很多答案,显示了如何在 python 方法中访问 json,但是我似乎无法让我的工作。

这是我的 ajax 调用

var data = {
        'customer': customer,
        'custID': custID,
        'date': date,
        'jobNum': jobNum,
        'deviceID': deviceID
    }

//create customer
if (custID === undefined) {
    $.ajax({
        url: "http://127.0.0.1:6543/test",
        type: "POST",
        data: JSON.stringify(data),
        dataType: 'json',
        success: function(response, textStatus, jqXHR) {
            alert(response);
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert(textStatus, errorThrown);
        }
    });
}
else {
    //empty
}

这是我的python方法:

@view_config(route_name="test", renderer='templates/main.html')
def new_sheet(request):
    response = request.POST
    myObject = json.loads(response)

    #print myObject["customer"]

    test = "hello"
    return dict(test=test)

对 python 有点陌生,所以请原谅我有限的理解。如何获取我的 json 并访问对象属性?当我尝试打印时,我在 cmd 中得到的只是ValueError: No JSON object could be decoded

【问题讨论】:

  • 为什么不使用data: data,然后将每个元素作为单独的POST元素访问?
  • @Barmar:这有其局限性。发送 JSON 是一个非常好的目标,尤其是当您想要发送结构化数据时。

标签: python ajax json pyramid


【解决方案1】:

pyramid 具有原生 JSON 请求支持。将contentType 参数设置为application/json 以告诉服务器您正在发送JSON,最好使用字符集(UTF8):

$.ajax({
    url: "http://127.0.0.1:6543/test",
    type: "POST",
    data: JSON.stringify(data),
    contentType: 'application/json; charset=utf-8'
    dataType: 'json',
    success: function(response, textStatus, jqXHR) {
        alert(response);
    },
    error: function(jqXHR, textStatus, errorThrown){
        alert(textStatus, errorThrown);
    }
});

在服务器端使用request.json_body:

@view_config(route_name="test", renderer='templates/main.html')
def new_sheet(request):
    myObject = request.json_body

    print myObject["customer"]

    test = "hello"
    return dict(test=test)

【讨论】:

  • 谢谢您,先生的工作就像一个魅力。你会碰巧有一个链接到request.json_body的进一步解释吗?
  • @john:我已经包含了文档的链接;它也链接到narrative documentation on JSON requests
猜你喜欢
  • 2017-11-03
  • 1970-01-01
  • 2013-05-03
  • 1970-01-01
  • 2016-11-05
  • 2020-01-07
  • 2023-03-03
  • 2020-07-31
相关资源
最近更新 更多