gpt4 book ai didi

python - 无法从python方法访问json对象

转载 作者:行者123 更新时间:2023-12-01 05:12:27 25 4
gpt4 key购买 nike

我看过很多答案,显示如何在 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:无法解码JSON对象

最佳答案

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)

关于python - 无法从python方法访问json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23894638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com