In another answer, someone mentioned the W3 working draft, which is now outdated, and the new version of the document says that we can use enctype="application/json" for the form and it will send whole form fields as properties of the object.
It’s still not clear to me how to send an array, but referring to the above document, you can send an object just like:
<form enctype='application/json'> <input name='name' value='Bender'> <select name='hind'> <option selected>Bitable</option> <option>Kickable</option> </select> <input type='checkbox' name='shiny' checked> </form> // produces {"name": "Bender", "hind": "Bitable", "shiny": true}
I cannot copy the entire document here, so look at the document to learn how to create more complex objects using array entries and parsing arrays in input field names.
To create a form from your object, you must make a series of input elements that produce the same JSON object that you have in your hands. You can do this manually or, if your object is large enough, you can use a piece of code to convert your object into the desired input elements. I ended up with something like the code below as a basis. You can change it as you like (for example, make the form hidden or even create more diverse types of input fields with styles for different types of properties for the real correct form)
(function () { const json = { bool: false, num: 1.5, str: 'ABC', obj: {b:true, n: .1, s: '2', a: [1, '1']}, arr: [ true, 500.33, 'x', [1, 2], {b:true, n: .1, s: '2', a: [1, '1']} ] }; const getFieldHTML = (value, name) => { if (name||name===0) switch (typeof value) { case 'boolean': return '<input type="checkbox" name="${name}" ${value?'checked':''}>\n'; case 'number': return '<input type="number" name="${name}" value="${value}">\n'; case 'string': return '<input type="text" name="${name}" value="${value}">\n'; } return ''; }; const getFieldsHTML = (value, name) => { const fields = []; if (value instanceof Array) fields.push(...value.map((itemValue, i) => getFieldsHTML(itemValue, name+'['+i+']') )); else if (typeof value === "object") fields.push(...Object.keys(value).map(prop => getFieldsHTML( value[prop],
Check your browser console to inspect the created form DOM and its children.
source share