我有一个使用此命名约定输入的表单:
<input class="xxlarge" name="note[url]" id="url" placeholder="URL">
所以,我正在使用 this script (在 StackOverflow 上找到)将表单数据序列化为 JSON。
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.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;
};
在输出中我有这个:
{"note[url]":"URL","note[title]":"TITLE"}
我想知道如何转换此脚本以获得如下输出:
{"url":"URL","title":"TITLE"}
我使用相当标准的、记录的代码块来处理这个问题(使用函数,如上所述):
$(function() {
$('form').submit(function() {
$('#result').html(JSON.stringify($('form').serializeObject()));
$.post(
"/api/create",
JSON.stringify($('form').serializeObject()),
function(responseText){
$("#result").html(responseText);
},
"html"
);
return false;
});
提前致谢!
最佳答案
我建议将字符串解析为 JS 对象,更改 for 循环中的键,然后在完成后将其字符串化。就像这样:
// turn the string into a JS object
var data = JSON.parse('{"note[url]":"URL","note[title]":"TITLE"}');
var newData = {};
// step through each member
for(key in data) {
// Regular expressions to find the brackets
var newKeyStart = key.search(/note\[/) + 5;
var newKeyEnd = key.search(/\]/);
// pull out the desired part of the key
var newKey = key.substr(newKeyStart, newKeyEnd - newKeyStart);
// insert into new data object
newData[newKey] = data[key];
}
// turn back into JSON again
var newJSON = JSON.stringify(newData);
关于javascript - 对 JSON 键进行子串化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7576125/