var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
var json = JSON.stringify(object);
// Or ES6 arrow function
var object = {};
formData.forEach((value, key) => object[key] = value);
var json = JSON.stringify(object);
function jsonToFormData (json){
const FORM_DATA = new FormData();
if(!json) return FORM_DATA;
try{
json = JSON.parse(json);
}catch{}
if(typeof json != 'object'||Array.isArray(json)) return FORM_DATA;
for(key in json) {
let value = json[key];
if(Array.isArray(value)){
value.forEach((v)=>{
FORM_DATA.append(key+"[]", v);
});
}
else
FORM_DATA.append(key, typeof json[key] == 'object' ? JSON.stringify(json[key]) : json[key]);
}
return FORM_DATA;
}
function buildFormData(formData, data, parentKey) {
if (data && typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) {
Object.keys(data).forEach(key => {
buildFormData(formData, data[key], parentKey ? `${parentKey}[${key}]` : key);
});
} else {
const value = data == null ? '' : data;
formData.append(parentKey, value);
}
}
function jsonToFormData(data) {
const formData = new FormData();
buildFormData(formData, data);
return formData;
}
const my_data = {
num: 1,
falseBool: false,
trueBool: true,
empty: '',
und: undefined,
nullable: null,
date: new Date(),
name: 'str',
another_object: {
name: 'my_name',
value: 'whatever'
},
array: [
{
key1: {
name: 'key1'
}
}
]
};
jsonToFormData(my_data)
function formDataToJson(formData){
let json = {};
if(!(formData instanceof FormData)) return json;
formData.forEach((value,key)=>{
json[key] = value;
});
return json;
}
var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
var json = JSON.stringify(object);
`const formDataObject = (formData) => {
for (const key in formData) {
if (formData[key].startsWith('{') || formData[key].startsWith('[')) {
try {
formData[key] = JSON.parse(formData[key]);
console.log("key is :", key, "form data is :", formData[key]);
} catch (error) {
console.log("error :", key);
}
}
}
console.log("object", formData)
}`