“Daten zu JSON bilden” Code-Antworten

Formdata zu 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);
yusuf_fazeri

json zu formdata

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;
}
2589

json zu 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)
Smiling Swan

Daten zu JSON bilden

function formDataToJson(formData){
    let json = {};
    if(!(formData instanceof FormData)) return json;
    formData.forEach((value,key)=>{
        json[key] = value;
    });
    return json;
}
2589

HTML -Daten zu JSON Formaten

var formData= new FormData(form)
JSON.stringify(Object.fromEntries(formData))
patrick204nqh

Ähnliche Antworten wie “Daten zu JSON bilden”

Fragen ähnlich wie “Daten zu JSON bilden”

Weitere verwandte Antworten zu “Daten zu JSON bilden” auf JavaScript

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen