繁体   English   中英

从HTML表单生成JSON

[英]Generate JSON from HTML form

我想在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"}]

您可以遍历数组元素,并使用预期格式的数据构造一个对象,

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,则第二个解决方案应该更具可持续性。

这似乎是一个奇怪的JSON对象,但是如果您将输入的name属性中的某些信息分解为data属性,可以采用以下方法:

 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> 

似乎目前浏览器不支持enctype ='application / json'(或其他任何与此有关的东西)。 根据我的理解,这只是对标准的建议,但由于安全/性能方面的考虑,它在大约4年前被废弃了。

我也认为下面的代码是一种更简单的方法(只需一步即可完成)

$('#result')。html(JSON.stringify($(“#form”)。serializeArray()));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM