【发布时间】:2021-01-07 17:04:51
【问题描述】:
我有一个表单,我正在使用 Ajax 向 API 提交数据。该表单包含一个重复器,可帮助用户重复输入任意数量的数据。用户在几个步骤后提交表单。当我尝试将值绑定到 Object 时未绑定。 API 是使用 Spring Boot 构建的,默认情况下,Jackson 用于将 JSON 转换为 Objects。
这是完整的代码,
f.submit(function(e){
e.preventDefault();
var ignoreFields = ["_csrf"];
var unindexed_array = $(this).serializeArray().filter(val => ignoreFields.indexOf(val.name) === -1);
var indexed_array = {};
$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});
$.ajax({
type: $(this).attr('method'),
contentType: 'application/json',
url: $(this).attr('action'),
data: JSON.stringify(indexed_array),
dataType: 'json', cache: false, timeout: 600000,
success: function (d) {
}, error: function (e) {
}
});
})
在 JSON.stringify() 之前
{
act1[0].quantity: "4",
act1[0].name: "abc",
act1[0].status: "Working",
act2[0].quantity: "5",
act2[0].id: "1",
act3[0].quantity: "4",
act3[0].id: "2",
act3[0].unit: "mm",
activity: "zdzdsd zsdsad",
endTime: "23:02",
location: "sdasd",
note: "sdfsdfsd sdfsdfsd",
startTime: "03:03"
}
如果我将上述代码转换为以下格式,我希望它可以工作,因为我使用的是列表,杰克逊图书馆将能够识别这种格式
{
endTime: "23:02",
location: "sdasd",
note: "sdfsdfsd sdfsdfsd",
startTime: "03:03",
act1:[{
quantity: "4",
name: "abc",
status: "Working"
}],
act2:[{
quantity: "5"
id: "1"
}],
act3:[{
quantity: "4"
id: "2",
unit: "mm"
}]
}
我在Javascript中尝试了很多方法来转换成这种格式,我们如何才能实现上述格式?
【问题讨论】:
-
您在这里尝试做什么有点不清楚。我不确定你的输入是什么,你的输出是什么。并且这两个样本都不是对象的合法 JS 表示(尽管后者如果包裹在
{-}中。你想将什么转换成什么?你能告诉我们一些你尝试过的东西吗? -
@ScottSauyet我修改了我的问题,不知道你能不能看懂,我真的不知道怎么问这个,是格式问题,你看到的就是我需要的格式第一个是我拥有的格式。如何将第一个 JSON 转换为最后一个 JSON 格式?
-
您如何获得该输入?它是如图所示的多行字符串吗?因为它仍然不是合法的 JS 格式。对象键可以包含任何字符,但在源代码或 JSON 中,不允许使用除字母数字字符 /$ /_ 之外的任何字符,除非包装在字符串中。也就是说,这是不合法的:
{act1[0].quantity: "4"},但是这(将密钥包裹在字符串中)是合法的:{"act1[0].quantity": "4"}。
标签: javascript arrays json spring spring-boot