gpt4 book ai didi

python - 将 JSON 字符串转换回数组

转载 作者:太空宇宙 更新时间:2023-11-03 17:17:11 25 4
gpt4 key购买 nike

我通过 ajax 将浮点值的二维数组传递到我的views.py。我的 ajax 调用如下所示:

$.ajax({
method: "POST",
url: "introURL",
data: {
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
dsg_mtx : JSON.stringify(dsg_mtx),

},
success: function(data) {

document.getElementById("test").innerHTML = data; // echo response
},
error: function() {
alert ("Something went wrong");
}

我通过以下调用将数据拉到 View 中:

def introURL(request):
if request.is_ajax():
try:
designMtx = json.loads(request.POST['dsg_mtx'], parse_float=None)

except KeyError:
return HttpResponse('Error, intro import')

... Some transformation of designMtx...


return HttpResponse(response)
else:
raise Http404

所以我的问题是如何将这个 json 字符串化对象转换回二维数组,我可以用它来计算响应?正如您所看到的,我尝试使用 parse_float 选项,但它仍然是 str 数据类型。

传递的数组 dsg_mtx 是使用 Handson 表创建的,如下所示:

-1  -1
-1 1
1 -1
1 1

感谢您的指导。

最佳答案

我的问题是handsontable 的默认设置。当我向表提供浮点值时,默认情况下,表将它们转换为字符串。所以我发布了一个看起来像 float 的字符串矩阵。修复方法只是重新格式化放置数据的可手动单元格。

var data = function () {
return Handsontable.helper.createSpreadsheetData(mtxrows, mtxcols);
};

var hot = new Handsontable(container, {
data: data,
height: 480,
colHeaders: true,
rowHeaders: true,
stretchH: 'none',
columnSorting: true,
contextMenu: true,
className: "htCenter",
cells: function (row, col, prop) {
var cellProperties = {};
if (row > 0) {
cellProperties.type = 'numeric';
cellProperties.format = '0[.]000';
}
return cellProperties;
},

afterChange: function () {
var tmpData = JSON.parse(JSON.stringify(mtx_data));
}
});

所以基本上第一行之后的任何内容都设置为数字类型。

现在我的 ajax 调用中的这一行:

dsg_mtx : JSON.stringify(dsg_mtx),

正确格式化它,views.py 使用此调用正确加载它:

designMtx = json.loads(request.POST['dsg_mtx'])

感谢 Tomasz Jakub 建议使用 console.log() 来帮助我诊断问题。

问候,海梅

关于python - 将 JSON 字符串转换回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33560932/

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