Covert form data to JSON string

后端 未结 6 1349
一个人的身影
一个人的身影 2020-12-19 22:07

If I

相关标签:
6条回答
  • 2020-12-19 22:53

    You can pass the <form> to FormData(), iterate key, value pairs of FormData instance, set each key and value to an object property and value

    let form = document.forms["test"];
    
    let fd = new FormData(form);
    
    let data = {};
    
    for (let [key, prop] of fd) {
      data[key] = prop;
    }
    
    data = JSON.stringify(data, null, 2);
    
    console.log(data);
    <form name='test'>
      <input type='text' name='login' value="a login">
      <input type='email' name='email' value="a email">
    </form>

    0 讨论(0)
  • 2020-12-19 23:01

    real quick solution that utilizes .serializeArray() would be:

    var objArr = JSON.serialize($(form)).serializeArray();
    var obj = objArr.pop();
    var strJson = JSON.serialize(obj);
    
    0 讨论(0)
  • 2020-12-19 23:02

    If you want javascript object:

     let dest = {};
     $( form )
         .serializeArray()
         .map( input => dest[ input.name ] = input.value );
    

    And the Json:

     console.log( JSON.stringify( dest ) );
    
    0 讨论(0)
  • 2020-12-19 23:03

    You could use this:

    JSON.stringify($(form).serializeArray().reduce((acc, f) => {
      acc[f.name] = f.value
      return acc
    }, {})
    
    0 讨论(0)
  • 2020-12-19 23:07

    Another way to do this, using plain js and form.elements as an argument to Array.reduce

    var d = [].reduce.call(document.forms['test'].elements,(a,b)=>(a[b.name]=b.value,a),{});
    var j = JSON.stringify(d, 0, 4);
    
    console.log(j);
    <form name='test'>
      <input type='text' name='login'>
      <input type='email' name='email'>
    </form>

    Using jQuery

    var data = $('form :input').toArray().reduce( (a,b) => (a[b.name]=b.value,a),{})
    var json = JSON.stringify(data,0,4);
    
    console.log(data);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form name='test'>
      <input type='text' name='login'>
      <input type='email' name='email'>
    </form>

    0 讨论(0)
  • 2020-12-19 23:08

    if you get this

    [{"name":"login","value":"a value"},{"name":"email","value":"a email"}];

    and you need just

    {"name":"login","value":"a value"}
    

    just call the variable by their index

    var data = [{"name":"login","value":"a value"},{"name":"email","value":"a email"}];
    
    console.log( data[0] )

    0 讨论(0)
提交回复
热议问题