我想在html表单上创建一个json:
<form enctype='application/json'>
<input name='pet[0][species]' value='Dahut'>
<input name='pet[0][name]' value='Hypatia'>
<input name='pet[1][species]' value='Felis Stultus'>
<input name='pet[1][name]' value='Billie'>
</form>
从上面的html中,我希望获得以下json:
// produces
{
"pet": [
{
"species": "Dahut"
, "name": "Hypatia"
}
, {
"species": "Felis Stultus"
, "name": "Billie"
}
]
}
不需要以下代码:
function serializeForm()
{
var jsonData = $('form').serializeArray();
var jsonString = JSON.stringify(jsonData);
$('#result').html(jsonString);
}
但是,不幸的是,我得到了以下json:
[{"name":"pet[0][species]","value":"Dahut"},{"name":"pet[0][name]","value":"Hypatia"},{"name":"pet[1][species]","value":"Felis Stultus"},{"name":"pet[1][name]","value":"Billie"}]
答案 0 :(得分:0)
您可以遍历数组元素并使用预期格式的数据构造一个对象,
let data = {};
$form.serializeArray().forEach(field => {
// Work on the data here to get the expected result
});
return data;
但是,我认为,如果您愿意在表单中添加一些额外的HTML,那么结果将是更可持续的代码。
如果使用服务器端应用程序使用数据库中的数据生成表单,则可以添加两个数据字段,并使用它们来提取期望格式的数据,
function serializeForm() {
let jsonData = {
pet: []
},
i = 0,
$inputs = $('input[data-pet-id=' + i + ']');
while ($inputs.length) {
let pet = {
species: $inputs.filter('input[data-field="species"]').val(),
name: $inputs.filter('input[data-field="name"]').val()
};
jsonData.pet[i] = pet;
i++;
$inputs = $('input[data-pet-id=' + i + ']');
}
console.log(jsonData);
$('#result').html(JSON.stringify(jsonData));
}
$('document').ready(() => {
serializeForm();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id='my-form' enctype='application/json'>
<input name='pet[0][species]' value='Dahut' data-pet-id="0" data-field='species'>
<input name='pet[0][name]' value='Hypatia' data-pet-id="0" data-field='name'>
<input name='pet[1][species]' value='Felis Stultus' data-pet-id="1" data-field='species'>
<input name='pet[1][name]' value='Billie' data-pet-id="1" data-field='name'>
</form>
<div id="result">Working...</div>
从长远来看,假设您以编程方式生成HTML,则第二个解决方案应该更具可持续性。
答案 1 :(得分:0)
这似乎是一个奇怪的JSON对象,但是如果您将输入的name
属性中的某些信息分解为数据属性,则可以采用以下方法:
const petInputs = document.getElementsByName("pet");
const buildBtn = document.getElementById("build");
buildBtn.addEventListener("click", buildJSON);
function buildJSON(){
// Defines `petsObj` for grouping information and `resultObj` for building result
const petsObj = {},
resultObj = { pet: [] };
// Groups information by pet id# (separates unique pets from each other)
for(let input of petInputs){
const type = input.dataset.type,
id = input.dataset.id;
if(!petsObj["id" + id]){ petsObj["id" + id] = {}; }
petsObj["id" + id][type] = input.value;
}
// Counts the number of unique pets
let petsCount = 0;
for(let pet in petsObj){ petsCount++; }
// Adds all pets to the `pet` property of the `json` object
for(let i = 0; i < petsCount; i++){ resultObj.pet.push(petsObj["id" + i]); }
// Prints and returns the JSON object
console.log(resultObj);
return(resultObj);
}
<input name="pet" data-type="species" data-id="0" value='Dahut'>
<input name="pet" data-type="name" data-id="0" value='Hypatia'><br />
<input name="pet" data-type="species" data-id="1" value='Felis Stultus'>
<input name="pet" data-type="name" data-id="1" value='Billie'><br />
<button id="build">Build JSON</button>
答案 2 :(得分:0)
目前看来浏览器不支持enctype ='application / json'(或其他任何与此有关的东西)。根据我的理解,这只是对标准的建议,但由于安全/性能方面的考虑,它在4年前被废弃了。
我还认为以下代码是一种更简单的执行方式(只需一步即可完成)
$('#result')。html(JSON.stringify($(“#form”)。serializeArray()));