Answers for "FormData to json"

1

FormData to json

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);
Posted by: Guest on December-12-2020
0

json to formData

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)
Posted by: Guest on April-18-2021
0

formData to Json

`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)
}`
Posted by: Guest on September-24-2021
0

How to convert FormData (HTML5 object) to JSON

var object = {};
formData.forEach(function(value, key){
    object[key] = value;
});
var json = JSON.stringify(object);
Posted by: Guest on June-12-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language