我如何将条目从HTML5 FormData对象转换为JSON?
解决方案不应该使用jQuery。而且,它不应该简单地序列化整个FormData对象,而应该只序列化它的键/值条目。
我如何将条目从HTML5 FormData对象转换为JSON?
解决方案不应该使用jQuery。而且,它不应该简单地序列化整个FormData对象,而应该只序列化它的键/值条目。
当前回答
使用JSON.stringify()中描述的toJSON
如果值具有toJSON()方法,则它负责定义将序列化的数据。
这里有一个小技巧。
var fd = new FormData(document.forms[0]); fd.toJSON = function() { const o = {}; this.forEach((v, k) => { v = this.getAll(k); o[k] = v.length == 1 ? v[0] : (v.length >= 1 ? v : null); }); return o; }; document.write(`<pre>${JSON.stringify(fd)}</pre>`) <form action="#"> <input name="name" value="Robinson" /> <input name="items" value="Vin" /> <input name="items" value="Fromage" /> <select name="animals" multiple id="animals"> <option value="tiger" selected>Tigre</option> <option value="turtle" selected>Tortue</option> <option value="monkey">Singe</option> </select> </form>
其他回答
如果您正在使用lodash,可以使用fropairs简单地完成
import {fromPairs} from 'lodash';
const object = fromPairs(Array.from(formData.entries()));
你可以试试这个
formDataToJSON($('#form_example'));
# Create a function to convert the serialize and convert the form data
# to JSON
# @param : $('#form_example');
# @return a JSON Stringify
function formDataToJSON(form) {
let obj = {};
let formData = form.serialize();
let formArray = formData.split("&");
for (inputData of formArray){
let dataTmp = inputData.split('=');
obj[dataTmp[0]] = dataTmp[1];
}
return JSON.stringify(obj);
}
这里有一种更函数化的方式,不需要使用库。
Array.from(formData.entries()).reduce((memo, [key, value]) => ({
...memo,
[key]: value,
}), {});
例子:
. getelementbyid(“foobar”)。addEventListener('submit', (e) => { e.preventDefault (); const formData = new formData (e.target); const data = Array.from(formData.entries()).reduce((memo, [key, value]) => ({ 备忘录, (例子):值, }, {}); . getelementbyid(“输出”)。innerHTML = JSON.stringify(数据); }); <形式id =“foobar”> <input name='baz' /> <input type='submit' /> > < /形式 <pre id='output'>输入一些值并提交</pre>
如果你有多个相同名称的条目,例如如果你使用<SELECT multiple>或有多个<INPUT type="checkbox">具有相同的名称,你需要注意这一点,并将值创建一个数组。否则只能得到最后选中的值。
以下是es6的现代版本:
function formToJSON( elem ) {
let output = {};
new FormData( elem ).forEach(
( value, key ) => {
// Check if property already exist
if ( Object.prototype.hasOwnProperty.call( output, key ) ) {
let current = output[ key ];
if ( !Array.isArray( current ) ) {
// If it's not an array, convert it to an array.
current = output[ key ] = [ current ];
}
current.push( value ); // Add the new value to the array.
} else {
output[ key ] = value;
}
}
);
return JSON.stringify( output );
}
稍旧的代码(但IE11仍然不支持,因为它不支持ForEach或FormData上的条目)
function formToJSON( elem ) {
var current, entries, item, key, output, value;
output = {};
entries = new FormData( elem ).entries();
// Iterate over values, and assign to item.
while ( item = entries.next().value )
{
// assign to variables to make the code more readable.
key = item[0];
value = item[1];
// Check if key already exist
if (Object.prototype.hasOwnProperty.call( output, key)) {
current = output[ key ];
if ( !Array.isArray( current ) ) {
// If it's not an array, convert it to an array.
current = output[ key ] = [ current ];
}
current.push( value ); // Add the new value to the array.
} else {
output[ key ] = value;
}
}
return JSON.stringify( output );
}
如果需要支持序列化嵌套字段(类似于PHP处理表单字段的方式),可以使用以下函数
function update(data, keys, value) { if (keys.length === 0) { // Leaf node return value; } let key = keys.shift(); if (!key) { data = data || []; if (Array.isArray(data)) { key = data.length; } } // Try converting key to a numeric value let index = +key; if (!isNaN(index)) { // We have a numeric index, make data a numeric array // This will not work if this is a associative array // with numeric keys data = data || []; key = index; } // If none of the above matched, we have an associative array data = data || {}; let val = update(data[key], keys, value); data[key] = val; return data; } function serializeForm(form) { return Array.from((new FormData(form)).entries()) .reduce((data, [field, value]) => { let [_, prefix, keys] = field.match(/^([^\[]+)((?:\[[^\]]*\])*)/); if (keys) { keys = Array.from(keys.matchAll(/\[([^\]]*)\]/g), m => m[1]); value = update(data[prefix], keys, value); } data[prefix] = value; return data; }, {}); } document.getElementById('output').textContent = JSON.stringify(serializeForm(document.getElementById('form')), null, 2); <form id="form"> <input name="field1" value="Field 1"> <input name="field2[]" value="Field 21"> <input name="field2[]" value="Field 22"> <input name="field3[a]" value="Field 3a"> <input name="field3[b]" value="Field 3b"> <input name="field3[c]" value="Field 3c"> <input name="field4[x][a]" value="Field xa"> <input name="field4[x][b]" value="Field xb"> <input name="field4[x][c]" value="Field xc"> <input name="field4[y][a]" value="Field ya"> <input name="field5[z][0]" value="Field z0"> <input name="field5[z][]" value="Field z1"> <input name="field6.z" value="Field 6Z0"> <input name="field6.z" value="Field 6Z1"> </form> <h2>Output</h2> <pre id="output"> </pre>