我如何将条目从HTML5 FormData对象转换为JSON?
解决方案不应该使用jQuery。而且,它不应该简单地序列化整个FormData对象,而应该只序列化它的键/值条目。
我如何将条目从HTML5 FormData对象转换为JSON?
解决方案不应该使用jQuery。而且,它不应该简单地序列化整个FormData对象,而应该只序列化它的键/值条目。
当前回答
下面是一个将formData对象转换为json字符串的函数。
适用于多个条目和嵌套数组。 适用于编号和命名的输入名称数组。
例如,你可以有以下表单字段:
<select name="select[]" multiple></select>
<input name="check[a][0][]" type="checkbox" value="test"/>
用法:
let json = form2json(formData);
功能:
function form2json(data) {
let method = function (object,pair) {
let keys = pair[0].replace(/\]/g,'').split('[');
let key = keys[0];
let value = pair[1];
if (keys.length > 1) {
let i,x,segment;
let last = value;
let type = isNaN(keys[1]) ? {} : [];
value = segment = object[key] || type;
for (i = 1; i < keys.length; i++) {
x = keys[i];
if (i == keys.length-1) {
if (Array.isArray(segment)) {
segment.push(last);
} else {
segment[x] = last;
}
} else if (segment[x] == undefined) {
segment[x] = isNaN(keys[i+1]) ? {} : [];
}
segment = segment[x];
}
}
object[key] = value;
return object;
}
let object = Array.from(data).reduce(method,{});
return JSON.stringify(object);
}
其他回答
如果你有多个相同名称的条目,例如如果你使用<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 );
}
如果下列物品能满足你的需求,那你就很幸运了:
你想转换一个数组的数组,如[['key','value1'], ['key2','value2'](就像FormData给你的)到一个key->值对象,如{key1: 'value1', key2: 'value2'},并将其转换为JSON字符串。 你的目标浏览器/设备是最新的ES6解释器,或者是用babel之类的东西编译。 你想用最小的方法来完成。
下面是你需要的代码:
const data = new FormData(document.querySelector('form'));
const json = JSON.stringify(Array.from(data).reduce((o,[k,v])=>(o[k]=v,o),{}));
希望这能帮助到一些人。
简单易用的功能
我已经为此创建了一个函数
function FormDataToJSON(FormElement){
var formData = new FormData(FormElement);
var ConvertedJSON= {};
for (const [key, value] of formData.entries())
{
ConvertedJSON[key] = value;
}
return ConvertedJSON
}
示例使用
var ReceivedJSON = FormDataToJSON(document.getElementById('FormId'));
在这段代码中,我使用for循环创建了空JSON变量,我在每个迭代中都使用了从formData Object到JSON key的键。
你在GitHub上找到我的JS库中的此代码,如果需要改进,请建议我,我已经在这里放置了代码https://github.com/alijamal14/Utilities/blob/master/Utilities.js
多年后的香草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'}
如果需要支持序列化嵌套字段(类似于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>