我如何将条目从HTML5 FormData对象转换为JSON?
解决方案不应该使用jQuery。而且,它不应该简单地序列化整个FormData对象,而应该只序列化它的键/值条目。
我如何将条目从HTML5 FormData对象转换为JSON?
解决方案不应该使用jQuery。而且,它不应该简单地序列化整个FormData对象,而应该只序列化它的键/值条目。
当前回答
对于我的目的,包括多选,如复选框,这是很好的:
JSON.stringify(Array.from((new FormData(document.querySelector('form'))).entries()).reduce((map = {}, [key, value]) => {
return {
...map,
[key]: map[key] ? [...map[key], value] : value,
};
}, {}));
其他回答
如果你有多个相同名称的条目,例如如果你使用<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 );
}
多年后的香草ajs (es6)
let body = new FormData()
body.set('key1', 'value AA')
body.set('key2', 'value BB')
let data = [...body.keys()].reduce( (acc, key, idx) => {
acc[key] = body.get(key)
return acc
} , {} )
console.log(JSON.stringify(data)) // {key1: 'value AA', key2: 'value BB'}
如果您正在使用lodash,可以使用fropairs简单地完成
import {fromPairs} from 'lodash';
const object = fromPairs(Array.from(formData.entries()));
对于我的目的,包括多选,如复选框,这是很好的:
JSON.stringify(Array.from((new FormData(document.querySelector('form'))).entries()).reduce((map = {}, [key, value]) => {
return {
...map,
[key]: map[key] ? [...map[key], value] : value,
};
}, {}));
另一种适用于选择多个或具有相同name属性的输入的方法:
function form_to_json() { const form_data = new FormData(document.querySelector('form')) const uniqueKeys = [...new Set(form_data.keys())] const obj = {} uniqueKeys.forEach((value, key) => { obj[value] = (form_data.getAll(value).length > 1) ? form_data.getAll(value) : form_data.get(value) }) const json = JSON.stringify(obj) alert(json) } <form> <input type="text" name="name" value="Cesar"></br> <select name="cars" id="cars" multiple> <option value="volvo" selected>Volvo</option> <option value="saab" selected>Saab</option> </select> <input type="button" onclick="form_to_json()" value="Ok"> </form>