Serialize nested field names to JSON
Turns names like user[name] and tags[] into a real nested object, ready to send as JSON.
jQuery · Serialize nested field names to JSONAdvanced
$.fn.toJSONObject = function () {
const result = {};
$.each(this.serializeArray(), function (i, f) {
const path = f.name.replace(/\]/g, '').split('['); // user[name] -> ['user', 'name']
let node = result;
path.forEach(function (key, idx) {
const last = idx === path.length - 1;
if (key === '') { (node.__arr = node.__arr || []).push(f.value); return; }
if (last) node[key] = f.value;
else node = node[key] = node[key] || (path[idx + 1] === '' ? [] : {});
});
});
(function fix(o) {
$.each(o, function (k, v) { if (v && typeof v === 'object') fix(v); });
})(result);
return result;
};
$.ajax({ url: '/api/user', method: 'POST', contentType: 'application/json', data: JSON.stringify($('#f').toJSONObject()) });formjsonnestedserializeArray