我有这样的序列化数组
rate_3=26&rate_8=67&rate_12=98
等等...,
现在我需要将此数组更改为 json 类型
{
"ID": "3",
"Rate": "26"
},
{
"ID": "8",
"Rate": "67"
},
{
"ID": "3",
"Rate": "26"
} ..,
etc
所以我尝试了这样的方法,但它不起作用......请有人帮助我。
var o = {};
var a = table.$('input, select').serialize();
$.each(a, function()
{
if (o[this.name] !== undefined)
{
if (!o[this.name].push)
{
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
}
else
{
o[this.name] = this.value || '';
}
});
return o;
我正在使用数据表,所以我只需要为使用此行的数据表序列化数组
var a = table.$('input, select').serialize();
即使我也尝试过使用 json2.js,但是当我使用 json2.js 时它会强制页面提交
var data_2 = JSON.stringify(block_form.serializeArray());
最佳答案
简单的方法就是map
在正则表达式匹配的结果上,将新对象推送到结果数组中:
var out = str.match(/\d+=\d+/g).map(function (el) {
var arr = el.split('=');
return { id: arr[0], rate: arr[1] };
});
使用 JSON.stringify(out)
将输出数组转换为 JSON。
关于javascript - 如何在 JavaScript 中将序列化数组值转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29898573/