How to convert FormData(HTML5 Object) to JSON









up vote
26
down vote

favorite
8












How to convert HTML5 FormData object to JSON? Without Jquery and handling nested properties in FormData like a object.










share|improve this question



















  • 1




    What are you trying to do? Does JSON.stringify() helps? Maybe you try to fix something that may be done in other way?
    – Justinas
    Jan 3 '17 at 7:39










  • Possible duplicate of Convert JS object to JSON string
    – Liam
    Jan 3 '17 at 8:54






  • 1




    Is not duplicate since I do not want to convert a javascript object to a json, nor do I want to use Jquery.serialize ()
    – Leonardo Villela
    Jan 3 '17 at 13:34














up vote
26
down vote

favorite
8












How to convert HTML5 FormData object to JSON? Without Jquery and handling nested properties in FormData like a object.










share|improve this question



















  • 1




    What are you trying to do? Does JSON.stringify() helps? Maybe you try to fix something that may be done in other way?
    – Justinas
    Jan 3 '17 at 7:39










  • Possible duplicate of Convert JS object to JSON string
    – Liam
    Jan 3 '17 at 8:54






  • 1




    Is not duplicate since I do not want to convert a javascript object to a json, nor do I want to use Jquery.serialize ()
    – Leonardo Villela
    Jan 3 '17 at 13:34












up vote
26
down vote

favorite
8









up vote
26
down vote

favorite
8






8





How to convert HTML5 FormData object to JSON? Without Jquery and handling nested properties in FormData like a object.










share|improve this question















How to convert HTML5 FormData object to JSON? Without Jquery and handling nested properties in FormData like a object.







javascript form-data






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 3 '17 at 7:34









Eugene Lisitsky

7,18221644




7,18221644










asked Jan 2 '17 at 18:00









Leonardo Villela

253148




253148







  • 1




    What are you trying to do? Does JSON.stringify() helps? Maybe you try to fix something that may be done in other way?
    – Justinas
    Jan 3 '17 at 7:39










  • Possible duplicate of Convert JS object to JSON string
    – Liam
    Jan 3 '17 at 8:54






  • 1




    Is not duplicate since I do not want to convert a javascript object to a json, nor do I want to use Jquery.serialize ()
    – Leonardo Villela
    Jan 3 '17 at 13:34












  • 1




    What are you trying to do? Does JSON.stringify() helps? Maybe you try to fix something that may be done in other way?
    – Justinas
    Jan 3 '17 at 7:39










  • Possible duplicate of Convert JS object to JSON string
    – Liam
    Jan 3 '17 at 8:54






  • 1




    Is not duplicate since I do not want to convert a javascript object to a json, nor do I want to use Jquery.serialize ()
    – Leonardo Villela
    Jan 3 '17 at 13:34







1




1




What are you trying to do? Does JSON.stringify() helps? Maybe you try to fix something that may be done in other way?
– Justinas
Jan 3 '17 at 7:39




What are you trying to do? Does JSON.stringify() helps? Maybe you try to fix something that may be done in other way?
– Justinas
Jan 3 '17 at 7:39












Possible duplicate of Convert JS object to JSON string
– Liam
Jan 3 '17 at 8:54




Possible duplicate of Convert JS object to JSON string
– Liam
Jan 3 '17 at 8:54




1




1




Is not duplicate since I do not want to convert a javascript object to a json, nor do I want to use Jquery.serialize ()
– Leonardo Villela
Jan 3 '17 at 13:34




Is not duplicate since I do not want to convert a javascript object to a json, nor do I want to use Jquery.serialize ()
– Leonardo Villela
Jan 3 '17 at 13:34












10 Answers
10






active

oldest

votes

















up vote
46
down vote



accepted










You could also use forEach on the FormData object directly:



var object = ;
formData.forEach(function(value, key)
object[key] = value;
);
var json = JSON.stringify(object);





share|improve this answer
















  • 1




    Seriously, this is the best implementation. Why isn't this the accepted answer?
    – ARun32
    Dec 2 '17 at 1:13






  • 1




    As mentioned in the answer from @TomasPrado make sure you don't need support for IE11.
    – Wilt
    Feb 23 at 8:44






  • 2




    This doesn't work with multi select form elements since they share the same key you end up overwriting the values returning only the last selected element
    – Sean
    Apr 2 at 5:18






  • 1




    @Sean I gave an answer that works with multiple values for <SELECT MULTIPLE> and <INPUT type="checkbox"> with same name, by converting the value to an array.
    – some
    Apr 14 at 0:32










  • formData is not a serie. how you can iterate? accepted answer but something missed.
    – Nuri YILMAZ
    Jun 28 at 15:24

















up vote
11
down vote













Here's a way to do it in a more functional style, without the use of a library.



Array.from(formData.entries()).reduce((memo, pair) => (
...memo,
[pair[0]]: pair[1],
), );




Example:






document.getElementById('foobar').addEventListener('submit', (e) => 
e.preventDefault();

const formData = new FormData(e.target);
const data = Array.from(formData.entries()).reduce((memo, pair) => (
...memo,
[pair[0]]: pair[1],
), );
document.getElementById('output').innerHTML = JSON.stringify(data);
);

<form id='foobar'>
<input name='baz' />
<input type='submit' />
</form>

<pre id='output'>Input some value and submit</pre>








share|improve this answer






















  • Best answer here. Thanks :)
    – TheDarkIn1978
    Aug 25 at 16:24










  • I really like this answer but still do not handle multiple items. I posted a new answer based on this one to handle those cases.
    – Carlos H.
    Nov 11 at 1:34

















up vote
6
down vote













If you have multiple entries with the same name, for example if you use <SELECT multiple> or have multiple <INPUT type="checkbox"> with the same name, you need to take care of that and make an array of the value. Otherwise you only get the last selected value.



Here is the modern ES6-variant:



function formToJSON( elem ) 
let output = ;
new FormData( elem ).forEach(
( value, key ) =>
// Check if property already exist
if ( Object.prototype.hasOwnProperty.call( output, key ) )
let current = output[ key ];
if ( !Array.isArray( current ) )
// If it's not an array, convert it to an array.
current = output[ key ] = [ current ];

current.push( value ); // Add the new value to the array.
else
output[ key ] = value;


);
return JSON.stringify( output );



Slightly older code (but still not supported by IE11, since it doesn't support ForEach or entries on FormData)



function formToJSON( elem ) 
var current, entries, item, key, output, value;
output = ;
entries = new FormData( elem ).entries();
// Iterate over values, and assign to item.
while ( item = entries.next().value )

// assign to variables to make the code more readable.
key = item[0];
value = item[1];
// Check if key already exist
if (Object.prototype.hasOwnProperty.call( output, key))
current = output[ key ];
if ( !Array.isArray( current ) )
// If it's not an array, convert it to an array.
current = output[ key ] = [ current ];

current.push( value ); // Add the new value to the array.
else
output[ key ] = value;


return JSON.stringify( output );






share|improve this answer



























    up vote
    4
    down vote













    You can achieve this by using the FormData() object. This FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content.



    Example:



    var myForm = document.getElementById('myForm');
    myForm.addEventListener('submit', function(event)

    event.preventDefault();
    var formData = new FormData(myForm),
    result = ;

    for (var entry of formData.entries())

    result[entry[0]] = entry[1];

    result = JSON.stringify(result)
    console.log(result);

    );





    share|improve this answer






















    • This does not produce json
      – Liam
      Jan 3 '17 at 8:54






    • 1




      @Liam Have you tried this with form elements ? And let me know why it doesn't produce JSON object ?
      – GiriB
      Jan 3 '17 at 9:37










    • There is no such thing as a json object. Json is a string notation
      – Liam
      Jan 3 '17 at 10:13






    • 1




      @Liam After the object created they can use JSON.stringify(result). And I have edited my answer. Please check it. And withdraw the down vote.
      – GiriB
      Jan 3 '17 at 14:10







    • 1




      You can also make the for of statement more expressive if you're using ES6: for (const [key, value] of formData.entries())
      – Teddy Zetterlund
      Mar 22 '17 at 8:15


















    up vote
    4
    down vote













    Easy To Use Function



    I Have Created A Function For This



    function FormDataToJSON(FormElement) 
    var formData = new FormData(FormElement);
    var ConvertedJSON= ;
    for (const [key, value] of formData.entries())

    ConvertedJSON[key] = value;


    return ConvertedJSON



    Example Usage



    var ReceivedJSON = FormDataToJSON(document.getElementById('FormId');)


    In this code I have created empty JSON variable using for loop I have used keys from formData Object to JSON Keys in every Itration.



    You Find This Code In My JS Library On GitHub Do Suggest Me If It Needs Improvement I Have Placed Code Here https://github.com/alijamal14/Utilities/blob/master/Utilities.js






    share|improve this answer


















    • 2




      Please explain your code.
      – zuluk
      May 24 '17 at 7:34






    • 1




      @zuluk Explained Thank You
      – Ali Jamal
      Sep 4 '17 at 20:26


















    up vote
    3
    down vote













    FormData method .entries and the for of expression is not supported in IE11 and Safari.



    Here is a simplier version to support Safari, Chrome, Firefox and Edge



    function formDataToJSON(formElement) 
    var formData = new FormData(formElement),
    convertedJSON = ;

    formData.forEach(function(value, key)
    convertedJSON[key] = value;
    );

    return convertedJSON;



    Warning: this answer doesn't work in IE11.

    FormData doesn't have a forEach method in IE11.

    I'm still searching for a final solution to support all major browsers.






    share|improve this answer






















    • this is perfect! we have to support older browsers and the iterator use is not very intuitive.
      – Peter Hawkins
      Dec 4 '17 at 14:21

















    up vote
    2
    down vote













    If you are using lodash it can be done concisely with fromPairs



    import fromPairs from 'lodash';

    const object = fromPairs(Array.from(formData.entries()));





    share|improve this answer



























      up vote
      1
      down vote













      This post is already a year old... but, I really, really like the ES6 @dzuc answer. However it is incomplete by not been able to handle multiple selects or checkboxes. This has already pointed and code solutions has been offered. I find them heavy and not optimized. So I wrote a 2 versions based on @dzuc to handle these cases:



      • For ASP style forms where multiple items name could just simple repeated.

      let r=Array.from(fd.entries()).reduce(
      (o , p) => (
      (!o[p[0]])
      ? ...o , [p[0]] : p[1]
      : ...o , [p[0]] : [...o[p[0]] , p[1]]
      )
      ,
      );
      let obj=JSON.stringify(r);


      One line Hotshot version:



      Array.from(fd.entries()).reduce((o,p)=>((!o[p[0]])?...o,[p[0]]:p[1]:...o,[p[0]]:[...o[p[0]],p[1]]),);


      • For PHP style forms where the multiple item names must have a suffix.

      let r=Array.from(fd.entries()).reduce(
      (o , p) => (
      (p[0].split('[').length>1)
      ? (p[0]=p[0].split('[')[0]
      , (!o[p[0]])
      ? ...o , [p[0]] : [p[1]]
      : ...o , [p[0]] : [...o[p[0]] , p[1] ]
      )
      : ...o , [p[0]] : p[1]
      )
      ,
      );
      let obj=JSON.stringify(r);


      One line Hotshot version:



      Array.from(fd.entries()).reduce((o,p)=>((p[0].split('[').length>1)?(p[0]=p[0].split('[')[0],(!o[p[0]])?...o,[p[0]]:[p[1]]:...o,[p[0]]:[...o[p[0]],p[1]]):...o,[p[0]]:p[1]),);





      share|improve this answer





























        up vote
        0
        down vote













        You can try this



        formDataToJSON($('#form_example'));

        # Create a function to convert the serialize and convert the form data
        # to JSON
        # @param : $('#form_example');
        # @return a JSON Stringify
        function formDataToJSON(form)
        let obj = ;
        let formData = form.serialize();
        let formArray = formData.split("&");

        for (inputData of formArray)
        let dataTmp = inputData.split('=');
        obj[dataTmp[0]] = dataTmp[1];

        return JSON.stringify(obj);






        share|improve this answer





























          up vote
          0
          down vote













          Even though the answer from @dzuc is already very good, you could use array destructuring (available in modern browsers or with Babel) to make it even a bit more elegant:



          // original version from @dzuc
          const data = Array.from(formData.entries())
          .reduce((memo, pair) => (
          ...memo,
          [pair[0]: pair[1],
          ), )

          // with array destructuring
          const data = Array.from(formData.entries())
          .reduce((memo,[key, value]) => (
          ...memo,
          [key]: value,
          ), )





          share|improve this answer




















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41431322%2fhow-to-convert-formdatahtml5-object-to-json%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            10 Answers
            10






            active

            oldest

            votes








            10 Answers
            10






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            46
            down vote



            accepted










            You could also use forEach on the FormData object directly:



            var object = ;
            formData.forEach(function(value, key)
            object[key] = value;
            );
            var json = JSON.stringify(object);





            share|improve this answer
















            • 1




              Seriously, this is the best implementation. Why isn't this the accepted answer?
              – ARun32
              Dec 2 '17 at 1:13






            • 1




              As mentioned in the answer from @TomasPrado make sure you don't need support for IE11.
              – Wilt
              Feb 23 at 8:44






            • 2




              This doesn't work with multi select form elements since they share the same key you end up overwriting the values returning only the last selected element
              – Sean
              Apr 2 at 5:18






            • 1




              @Sean I gave an answer that works with multiple values for <SELECT MULTIPLE> and <INPUT type="checkbox"> with same name, by converting the value to an array.
              – some
              Apr 14 at 0:32










            • formData is not a serie. how you can iterate? accepted answer but something missed.
              – Nuri YILMAZ
              Jun 28 at 15:24














            up vote
            46
            down vote



            accepted










            You could also use forEach on the FormData object directly:



            var object = ;
            formData.forEach(function(value, key)
            object[key] = value;
            );
            var json = JSON.stringify(object);





            share|improve this answer
















            • 1




              Seriously, this is the best implementation. Why isn't this the accepted answer?
              – ARun32
              Dec 2 '17 at 1:13






            • 1




              As mentioned in the answer from @TomasPrado make sure you don't need support for IE11.
              – Wilt
              Feb 23 at 8:44






            • 2




              This doesn't work with multi select form elements since they share the same key you end up overwriting the values returning only the last selected element
              – Sean
              Apr 2 at 5:18






            • 1




              @Sean I gave an answer that works with multiple values for <SELECT MULTIPLE> and <INPUT type="checkbox"> with same name, by converting the value to an array.
              – some
              Apr 14 at 0:32










            • formData is not a serie. how you can iterate? accepted answer but something missed.
              – Nuri YILMAZ
              Jun 28 at 15:24












            up vote
            46
            down vote



            accepted







            up vote
            46
            down vote



            accepted






            You could also use forEach on the FormData object directly:



            var object = ;
            formData.forEach(function(value, key)
            object[key] = value;
            );
            var json = JSON.stringify(object);





            share|improve this answer












            You could also use forEach on the FormData object directly:



            var object = ;
            formData.forEach(function(value, key)
            object[key] = value;
            );
            var json = JSON.stringify(object);






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Oct 16 '17 at 15:40









            Wilt

            21k886125




            21k886125







            • 1




              Seriously, this is the best implementation. Why isn't this the accepted answer?
              – ARun32
              Dec 2 '17 at 1:13






            • 1




              As mentioned in the answer from @TomasPrado make sure you don't need support for IE11.
              – Wilt
              Feb 23 at 8:44






            • 2




              This doesn't work with multi select form elements since they share the same key you end up overwriting the values returning only the last selected element
              – Sean
              Apr 2 at 5:18






            • 1




              @Sean I gave an answer that works with multiple values for <SELECT MULTIPLE> and <INPUT type="checkbox"> with same name, by converting the value to an array.
              – some
              Apr 14 at 0:32










            • formData is not a serie. how you can iterate? accepted answer but something missed.
              – Nuri YILMAZ
              Jun 28 at 15:24












            • 1




              Seriously, this is the best implementation. Why isn't this the accepted answer?
              – ARun32
              Dec 2 '17 at 1:13






            • 1




              As mentioned in the answer from @TomasPrado make sure you don't need support for IE11.
              – Wilt
              Feb 23 at 8:44






            • 2




              This doesn't work with multi select form elements since they share the same key you end up overwriting the values returning only the last selected element
              – Sean
              Apr 2 at 5:18






            • 1




              @Sean I gave an answer that works with multiple values for <SELECT MULTIPLE> and <INPUT type="checkbox"> with same name, by converting the value to an array.
              – some
              Apr 14 at 0:32










            • formData is not a serie. how you can iterate? accepted answer but something missed.
              – Nuri YILMAZ
              Jun 28 at 15:24







            1




            1




            Seriously, this is the best implementation. Why isn't this the accepted answer?
            – ARun32
            Dec 2 '17 at 1:13




            Seriously, this is the best implementation. Why isn't this the accepted answer?
            – ARun32
            Dec 2 '17 at 1:13




            1




            1




            As mentioned in the answer from @TomasPrado make sure you don't need support for IE11.
            – Wilt
            Feb 23 at 8:44




            As mentioned in the answer from @TomasPrado make sure you don't need support for IE11.
            – Wilt
            Feb 23 at 8:44




            2




            2




            This doesn't work with multi select form elements since they share the same key you end up overwriting the values returning only the last selected element
            – Sean
            Apr 2 at 5:18




            This doesn't work with multi select form elements since they share the same key you end up overwriting the values returning only the last selected element
            – Sean
            Apr 2 at 5:18




            1




            1




            @Sean I gave an answer that works with multiple values for <SELECT MULTIPLE> and <INPUT type="checkbox"> with same name, by converting the value to an array.
            – some
            Apr 14 at 0:32




            @Sean I gave an answer that works with multiple values for <SELECT MULTIPLE> and <INPUT type="checkbox"> with same name, by converting the value to an array.
            – some
            Apr 14 at 0:32












            formData is not a serie. how you can iterate? accepted answer but something missed.
            – Nuri YILMAZ
            Jun 28 at 15:24




            formData is not a serie. how you can iterate? accepted answer but something missed.
            – Nuri YILMAZ
            Jun 28 at 15:24












            up vote
            11
            down vote













            Here's a way to do it in a more functional style, without the use of a library.



            Array.from(formData.entries()).reduce((memo, pair) => (
            ...memo,
            [pair[0]]: pair[1],
            ), );




            Example:






            document.getElementById('foobar').addEventListener('submit', (e) => 
            e.preventDefault();

            const formData = new FormData(e.target);
            const data = Array.from(formData.entries()).reduce((memo, pair) => (
            ...memo,
            [pair[0]]: pair[1],
            ), );
            document.getElementById('output').innerHTML = JSON.stringify(data);
            );

            <form id='foobar'>
            <input name='baz' />
            <input type='submit' />
            </form>

            <pre id='output'>Input some value and submit</pre>








            share|improve this answer






















            • Best answer here. Thanks :)
              – TheDarkIn1978
              Aug 25 at 16:24










            • I really like this answer but still do not handle multiple items. I posted a new answer based on this one to handle those cases.
              – Carlos H.
              Nov 11 at 1:34














            up vote
            11
            down vote













            Here's a way to do it in a more functional style, without the use of a library.



            Array.from(formData.entries()).reduce((memo, pair) => (
            ...memo,
            [pair[0]]: pair[1],
            ), );




            Example:






            document.getElementById('foobar').addEventListener('submit', (e) => 
            e.preventDefault();

            const formData = new FormData(e.target);
            const data = Array.from(formData.entries()).reduce((memo, pair) => (
            ...memo,
            [pair[0]]: pair[1],
            ), );
            document.getElementById('output').innerHTML = JSON.stringify(data);
            );

            <form id='foobar'>
            <input name='baz' />
            <input type='submit' />
            </form>

            <pre id='output'>Input some value and submit</pre>








            share|improve this answer






















            • Best answer here. Thanks :)
              – TheDarkIn1978
              Aug 25 at 16:24










            • I really like this answer but still do not handle multiple items. I posted a new answer based on this one to handle those cases.
              – Carlos H.
              Nov 11 at 1:34












            up vote
            11
            down vote










            up vote
            11
            down vote









            Here's a way to do it in a more functional style, without the use of a library.



            Array.from(formData.entries()).reduce((memo, pair) => (
            ...memo,
            [pair[0]]: pair[1],
            ), );




            Example:






            document.getElementById('foobar').addEventListener('submit', (e) => 
            e.preventDefault();

            const formData = new FormData(e.target);
            const data = Array.from(formData.entries()).reduce((memo, pair) => (
            ...memo,
            [pair[0]]: pair[1],
            ), );
            document.getElementById('output').innerHTML = JSON.stringify(data);
            );

            <form id='foobar'>
            <input name='baz' />
            <input type='submit' />
            </form>

            <pre id='output'>Input some value and submit</pre>








            share|improve this answer














            Here's a way to do it in a more functional style, without the use of a library.



            Array.from(formData.entries()).reduce((memo, pair) => (
            ...memo,
            [pair[0]]: pair[1],
            ), );




            Example:






            document.getElementById('foobar').addEventListener('submit', (e) => 
            e.preventDefault();

            const formData = new FormData(e.target);
            const data = Array.from(formData.entries()).reduce((memo, pair) => (
            ...memo,
            [pair[0]]: pair[1],
            ), );
            document.getElementById('output').innerHTML = JSON.stringify(data);
            );

            <form id='foobar'>
            <input name='baz' />
            <input type='submit' />
            </form>

            <pre id='output'>Input some value and submit</pre>








            document.getElementById('foobar').addEventListener('submit', (e) => 
            e.preventDefault();

            const formData = new FormData(e.target);
            const data = Array.from(formData.entries()).reduce((memo, pair) => (
            ...memo,
            [pair[0]]: pair[1],
            ), );
            document.getElementById('output').innerHTML = JSON.stringify(data);
            );

            <form id='foobar'>
            <input name='baz' />
            <input type='submit' />
            </form>

            <pre id='output'>Input some value and submit</pre>





            document.getElementById('foobar').addEventListener('submit', (e) => 
            e.preventDefault();

            const formData = new FormData(e.target);
            const data = Array.from(formData.entries()).reduce((memo, pair) => (
            ...memo,
            [pair[0]]: pair[1],
            ), );
            document.getElementById('output').innerHTML = JSON.stringify(data);
            );

            <form id='foobar'>
            <input name='baz' />
            <input type='submit' />
            </form>

            <pre id='output'>Input some value and submit</pre>






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Feb 20 at 19:43

























            answered Feb 20 at 19:36









            dzuc

            440510




            440510











            • Best answer here. Thanks :)
              – TheDarkIn1978
              Aug 25 at 16:24










            • I really like this answer but still do not handle multiple items. I posted a new answer based on this one to handle those cases.
              – Carlos H.
              Nov 11 at 1:34
















            • Best answer here. Thanks :)
              – TheDarkIn1978
              Aug 25 at 16:24










            • I really like this answer but still do not handle multiple items. I posted a new answer based on this one to handle those cases.
              – Carlos H.
              Nov 11 at 1:34















            Best answer here. Thanks :)
            – TheDarkIn1978
            Aug 25 at 16:24




            Best answer here. Thanks :)
            – TheDarkIn1978
            Aug 25 at 16:24












            I really like this answer but still do not handle multiple items. I posted a new answer based on this one to handle those cases.
            – Carlos H.
            Nov 11 at 1:34




            I really like this answer but still do not handle multiple items. I posted a new answer based on this one to handle those cases.
            – Carlos H.
            Nov 11 at 1:34










            up vote
            6
            down vote













            If you have multiple entries with the same name, for example if you use <SELECT multiple> or have multiple <INPUT type="checkbox"> with the same name, you need to take care of that and make an array of the value. Otherwise you only get the last selected value.



            Here is the modern ES6-variant:



            function formToJSON( elem ) 
            let output = ;
            new FormData( elem ).forEach(
            ( value, key ) =>
            // Check if property already exist
            if ( Object.prototype.hasOwnProperty.call( output, key ) )
            let current = output[ key ];
            if ( !Array.isArray( current ) )
            // If it's not an array, convert it to an array.
            current = output[ key ] = [ current ];

            current.push( value ); // Add the new value to the array.
            else
            output[ key ] = value;


            );
            return JSON.stringify( output );



            Slightly older code (but still not supported by IE11, since it doesn't support ForEach or entries on FormData)



            function formToJSON( elem ) 
            var current, entries, item, key, output, value;
            output = ;
            entries = new FormData( elem ).entries();
            // Iterate over values, and assign to item.
            while ( item = entries.next().value )

            // assign to variables to make the code more readable.
            key = item[0];
            value = item[1];
            // Check if key already exist
            if (Object.prototype.hasOwnProperty.call( output, key))
            current = output[ key ];
            if ( !Array.isArray( current ) )
            // If it's not an array, convert it to an array.
            current = output[ key ] = [ current ];

            current.push( value ); // Add the new value to the array.
            else
            output[ key ] = value;


            return JSON.stringify( output );






            share|improve this answer
























              up vote
              6
              down vote













              If you have multiple entries with the same name, for example if you use <SELECT multiple> or have multiple <INPUT type="checkbox"> with the same name, you need to take care of that and make an array of the value. Otherwise you only get the last selected value.



              Here is the modern ES6-variant:



              function formToJSON( elem ) 
              let output = ;
              new FormData( elem ).forEach(
              ( value, key ) =>
              // Check if property already exist
              if ( Object.prototype.hasOwnProperty.call( output, key ) )
              let current = output[ key ];
              if ( !Array.isArray( current ) )
              // If it's not an array, convert it to an array.
              current = output[ key ] = [ current ];

              current.push( value ); // Add the new value to the array.
              else
              output[ key ] = value;


              );
              return JSON.stringify( output );



              Slightly older code (but still not supported by IE11, since it doesn't support ForEach or entries on FormData)



              function formToJSON( elem ) 
              var current, entries, item, key, output, value;
              output = ;
              entries = new FormData( elem ).entries();
              // Iterate over values, and assign to item.
              while ( item = entries.next().value )

              // assign to variables to make the code more readable.
              key = item[0];
              value = item[1];
              // Check if key already exist
              if (Object.prototype.hasOwnProperty.call( output, key))
              current = output[ key ];
              if ( !Array.isArray( current ) )
              // If it's not an array, convert it to an array.
              current = output[ key ] = [ current ];

              current.push( value ); // Add the new value to the array.
              else
              output[ key ] = value;


              return JSON.stringify( output );






              share|improve this answer






















                up vote
                6
                down vote










                up vote
                6
                down vote









                If you have multiple entries with the same name, for example if you use <SELECT multiple> or have multiple <INPUT type="checkbox"> with the same name, you need to take care of that and make an array of the value. Otherwise you only get the last selected value.



                Here is the modern ES6-variant:



                function formToJSON( elem ) 
                let output = ;
                new FormData( elem ).forEach(
                ( value, key ) =>
                // Check if property already exist
                if ( Object.prototype.hasOwnProperty.call( output, key ) )
                let current = output[ key ];
                if ( !Array.isArray( current ) )
                // If it's not an array, convert it to an array.
                current = output[ key ] = [ current ];

                current.push( value ); // Add the new value to the array.
                else
                output[ key ] = value;


                );
                return JSON.stringify( output );



                Slightly older code (but still not supported by IE11, since it doesn't support ForEach or entries on FormData)



                function formToJSON( elem ) 
                var current, entries, item, key, output, value;
                output = ;
                entries = new FormData( elem ).entries();
                // Iterate over values, and assign to item.
                while ( item = entries.next().value )

                // assign to variables to make the code more readable.
                key = item[0];
                value = item[1];
                // Check if key already exist
                if (Object.prototype.hasOwnProperty.call( output, key))
                current = output[ key ];
                if ( !Array.isArray( current ) )
                // If it's not an array, convert it to an array.
                current = output[ key ] = [ current ];

                current.push( value ); // Add the new value to the array.
                else
                output[ key ] = value;


                return JSON.stringify( output );






                share|improve this answer












                If you have multiple entries with the same name, for example if you use <SELECT multiple> or have multiple <INPUT type="checkbox"> with the same name, you need to take care of that and make an array of the value. Otherwise you only get the last selected value.



                Here is the modern ES6-variant:



                function formToJSON( elem ) 
                let output = ;
                new FormData( elem ).forEach(
                ( value, key ) =>
                // Check if property already exist
                if ( Object.prototype.hasOwnProperty.call( output, key ) )
                let current = output[ key ];
                if ( !Array.isArray( current ) )
                // If it's not an array, convert it to an array.
                current = output[ key ] = [ current ];

                current.push( value ); // Add the new value to the array.
                else
                output[ key ] = value;


                );
                return JSON.stringify( output );



                Slightly older code (but still not supported by IE11, since it doesn't support ForEach or entries on FormData)



                function formToJSON( elem ) 
                var current, entries, item, key, output, value;
                output = ;
                entries = new FormData( elem ).entries();
                // Iterate over values, and assign to item.
                while ( item = entries.next().value )

                // assign to variables to make the code more readable.
                key = item[0];
                value = item[1];
                // Check if key already exist
                if (Object.prototype.hasOwnProperty.call( output, key))
                current = output[ key ];
                if ( !Array.isArray( current ) )
                // If it's not an array, convert it to an array.
                current = output[ key ] = [ current ];

                current.push( value ); // Add the new value to the array.
                else
                output[ key ] = value;


                return JSON.stringify( output );







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Apr 14 at 0:29









                some

                35k116379




                35k116379




















                    up vote
                    4
                    down vote













                    You can achieve this by using the FormData() object. This FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content.



                    Example:



                    var myForm = document.getElementById('myForm');
                    myForm.addEventListener('submit', function(event)

                    event.preventDefault();
                    var formData = new FormData(myForm),
                    result = ;

                    for (var entry of formData.entries())

                    result[entry[0]] = entry[1];

                    result = JSON.stringify(result)
                    console.log(result);

                    );





                    share|improve this answer






















                    • This does not produce json
                      – Liam
                      Jan 3 '17 at 8:54






                    • 1




                      @Liam Have you tried this with form elements ? And let me know why it doesn't produce JSON object ?
                      – GiriB
                      Jan 3 '17 at 9:37










                    • There is no such thing as a json object. Json is a string notation
                      – Liam
                      Jan 3 '17 at 10:13






                    • 1




                      @Liam After the object created they can use JSON.stringify(result). And I have edited my answer. Please check it. And withdraw the down vote.
                      – GiriB
                      Jan 3 '17 at 14:10







                    • 1




                      You can also make the for of statement more expressive if you're using ES6: for (const [key, value] of formData.entries())
                      – Teddy Zetterlund
                      Mar 22 '17 at 8:15















                    up vote
                    4
                    down vote













                    You can achieve this by using the FormData() object. This FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content.



                    Example:



                    var myForm = document.getElementById('myForm');
                    myForm.addEventListener('submit', function(event)

                    event.preventDefault();
                    var formData = new FormData(myForm),
                    result = ;

                    for (var entry of formData.entries())

                    result[entry[0]] = entry[1];

                    result = JSON.stringify(result)
                    console.log(result);

                    );





                    share|improve this answer






















                    • This does not produce json
                      – Liam
                      Jan 3 '17 at 8:54






                    • 1




                      @Liam Have you tried this with form elements ? And let me know why it doesn't produce JSON object ?
                      – GiriB
                      Jan 3 '17 at 9:37










                    • There is no such thing as a json object. Json is a string notation
                      – Liam
                      Jan 3 '17 at 10:13






                    • 1




                      @Liam After the object created they can use JSON.stringify(result). And I have edited my answer. Please check it. And withdraw the down vote.
                      – GiriB
                      Jan 3 '17 at 14:10







                    • 1




                      You can also make the for of statement more expressive if you're using ES6: for (const [key, value] of formData.entries())
                      – Teddy Zetterlund
                      Mar 22 '17 at 8:15













                    up vote
                    4
                    down vote










                    up vote
                    4
                    down vote









                    You can achieve this by using the FormData() object. This FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content.



                    Example:



                    var myForm = document.getElementById('myForm');
                    myForm.addEventListener('submit', function(event)

                    event.preventDefault();
                    var formData = new FormData(myForm),
                    result = ;

                    for (var entry of formData.entries())

                    result[entry[0]] = entry[1];

                    result = JSON.stringify(result)
                    console.log(result);

                    );





                    share|improve this answer














                    You can achieve this by using the FormData() object. This FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content.



                    Example:



                    var myForm = document.getElementById('myForm');
                    myForm.addEventListener('submit', function(event)

                    event.preventDefault();
                    var formData = new FormData(myForm),
                    result = ;

                    for (var entry of formData.entries())

                    result[entry[0]] = entry[1];

                    result = JSON.stringify(result)
                    console.log(result);

                    );






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jan 3 '17 at 14:11

























                    answered Jan 3 '17 at 8:52









                    GiriB

                    1165




                    1165











                    • This does not produce json
                      – Liam
                      Jan 3 '17 at 8:54






                    • 1




                      @Liam Have you tried this with form elements ? And let me know why it doesn't produce JSON object ?
                      – GiriB
                      Jan 3 '17 at 9:37










                    • There is no such thing as a json object. Json is a string notation
                      – Liam
                      Jan 3 '17 at 10:13






                    • 1




                      @Liam After the object created they can use JSON.stringify(result). And I have edited my answer. Please check it. And withdraw the down vote.
                      – GiriB
                      Jan 3 '17 at 14:10







                    • 1




                      You can also make the for of statement more expressive if you're using ES6: for (const [key, value] of formData.entries())
                      – Teddy Zetterlund
                      Mar 22 '17 at 8:15

















                    • This does not produce json
                      – Liam
                      Jan 3 '17 at 8:54






                    • 1




                      @Liam Have you tried this with form elements ? And let me know why it doesn't produce JSON object ?
                      – GiriB
                      Jan 3 '17 at 9:37










                    • There is no such thing as a json object. Json is a string notation
                      – Liam
                      Jan 3 '17 at 10:13






                    • 1




                      @Liam After the object created they can use JSON.stringify(result). And I have edited my answer. Please check it. And withdraw the down vote.
                      – GiriB
                      Jan 3 '17 at 14:10







                    • 1




                      You can also make the for of statement more expressive if you're using ES6: for (const [key, value] of formData.entries())
                      – Teddy Zetterlund
                      Mar 22 '17 at 8:15
















                    This does not produce json
                    – Liam
                    Jan 3 '17 at 8:54




                    This does not produce json
                    – Liam
                    Jan 3 '17 at 8:54




                    1




                    1




                    @Liam Have you tried this with form elements ? And let me know why it doesn't produce JSON object ?
                    – GiriB
                    Jan 3 '17 at 9:37




                    @Liam Have you tried this with form elements ? And let me know why it doesn't produce JSON object ?
                    – GiriB
                    Jan 3 '17 at 9:37












                    There is no such thing as a json object. Json is a string notation
                    – Liam
                    Jan 3 '17 at 10:13




                    There is no such thing as a json object. Json is a string notation
                    – Liam
                    Jan 3 '17 at 10:13




                    1




                    1




                    @Liam After the object created they can use JSON.stringify(result). And I have edited my answer. Please check it. And withdraw the down vote.
                    – GiriB
                    Jan 3 '17 at 14:10





                    @Liam After the object created they can use JSON.stringify(result). And I have edited my answer. Please check it. And withdraw the down vote.
                    – GiriB
                    Jan 3 '17 at 14:10





                    1




                    1




                    You can also make the for of statement more expressive if you're using ES6: for (const [key, value] of formData.entries())
                    – Teddy Zetterlund
                    Mar 22 '17 at 8:15





                    You can also make the for of statement more expressive if you're using ES6: for (const [key, value] of formData.entries())
                    – Teddy Zetterlund
                    Mar 22 '17 at 8:15











                    up vote
                    4
                    down vote













                    Easy To Use Function



                    I Have Created A Function For This



                    function FormDataToJSON(FormElement) 
                    var formData = new FormData(FormElement);
                    var ConvertedJSON= ;
                    for (const [key, value] of formData.entries())

                    ConvertedJSON[key] = value;


                    return ConvertedJSON



                    Example Usage



                    var ReceivedJSON = FormDataToJSON(document.getElementById('FormId');)


                    In this code I have created empty JSON variable using for loop I have used keys from formData Object to JSON Keys in every Itration.



                    You Find This Code In My JS Library On GitHub Do Suggest Me If It Needs Improvement I Have Placed Code Here https://github.com/alijamal14/Utilities/blob/master/Utilities.js






                    share|improve this answer


















                    • 2




                      Please explain your code.
                      – zuluk
                      May 24 '17 at 7:34






                    • 1




                      @zuluk Explained Thank You
                      – Ali Jamal
                      Sep 4 '17 at 20:26















                    up vote
                    4
                    down vote













                    Easy To Use Function



                    I Have Created A Function For This



                    function FormDataToJSON(FormElement) 
                    var formData = new FormData(FormElement);
                    var ConvertedJSON= ;
                    for (const [key, value] of formData.entries())

                    ConvertedJSON[key] = value;


                    return ConvertedJSON



                    Example Usage



                    var ReceivedJSON = FormDataToJSON(document.getElementById('FormId');)


                    In this code I have created empty JSON variable using for loop I have used keys from formData Object to JSON Keys in every Itration.



                    You Find This Code In My JS Library On GitHub Do Suggest Me If It Needs Improvement I Have Placed Code Here https://github.com/alijamal14/Utilities/blob/master/Utilities.js






                    share|improve this answer


















                    • 2




                      Please explain your code.
                      – zuluk
                      May 24 '17 at 7:34






                    • 1




                      @zuluk Explained Thank You
                      – Ali Jamal
                      Sep 4 '17 at 20:26













                    up vote
                    4
                    down vote










                    up vote
                    4
                    down vote









                    Easy To Use Function



                    I Have Created A Function For This



                    function FormDataToJSON(FormElement) 
                    var formData = new FormData(FormElement);
                    var ConvertedJSON= ;
                    for (const [key, value] of formData.entries())

                    ConvertedJSON[key] = value;


                    return ConvertedJSON



                    Example Usage



                    var ReceivedJSON = FormDataToJSON(document.getElementById('FormId');)


                    In this code I have created empty JSON variable using for loop I have used keys from formData Object to JSON Keys in every Itration.



                    You Find This Code In My JS Library On GitHub Do Suggest Me If It Needs Improvement I Have Placed Code Here https://github.com/alijamal14/Utilities/blob/master/Utilities.js






                    share|improve this answer














                    Easy To Use Function



                    I Have Created A Function For This



                    function FormDataToJSON(FormElement) 
                    var formData = new FormData(FormElement);
                    var ConvertedJSON= ;
                    for (const [key, value] of formData.entries())

                    ConvertedJSON[key] = value;


                    return ConvertedJSON



                    Example Usage



                    var ReceivedJSON = FormDataToJSON(document.getElementById('FormId');)


                    In this code I have created empty JSON variable using for loop I have used keys from formData Object to JSON Keys in every Itration.



                    You Find This Code In My JS Library On GitHub Do Suggest Me If It Needs Improvement I Have Placed Code Here https://github.com/alijamal14/Utilities/blob/master/Utilities.js







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Dec 14 '17 at 7:05

























                    answered May 24 '17 at 7:13









                    Ali Jamal

                    9212




                    9212







                    • 2




                      Please explain your code.
                      – zuluk
                      May 24 '17 at 7:34






                    • 1




                      @zuluk Explained Thank You
                      – Ali Jamal
                      Sep 4 '17 at 20:26













                    • 2




                      Please explain your code.
                      – zuluk
                      May 24 '17 at 7:34






                    • 1




                      @zuluk Explained Thank You
                      – Ali Jamal
                      Sep 4 '17 at 20:26








                    2




                    2




                    Please explain your code.
                    – zuluk
                    May 24 '17 at 7:34




                    Please explain your code.
                    – zuluk
                    May 24 '17 at 7:34




                    1




                    1




                    @zuluk Explained Thank You
                    – Ali Jamal
                    Sep 4 '17 at 20:26





                    @zuluk Explained Thank You
                    – Ali Jamal
                    Sep 4 '17 at 20:26











                    up vote
                    3
                    down vote













                    FormData method .entries and the for of expression is not supported in IE11 and Safari.



                    Here is a simplier version to support Safari, Chrome, Firefox and Edge



                    function formDataToJSON(formElement) 
                    var formData = new FormData(formElement),
                    convertedJSON = ;

                    formData.forEach(function(value, key)
                    convertedJSON[key] = value;
                    );

                    return convertedJSON;



                    Warning: this answer doesn't work in IE11.

                    FormData doesn't have a forEach method in IE11.

                    I'm still searching for a final solution to support all major browsers.






                    share|improve this answer






















                    • this is perfect! we have to support older browsers and the iterator use is not very intuitive.
                      – Peter Hawkins
                      Dec 4 '17 at 14:21














                    up vote
                    3
                    down vote













                    FormData method .entries and the for of expression is not supported in IE11 and Safari.



                    Here is a simplier version to support Safari, Chrome, Firefox and Edge



                    function formDataToJSON(formElement) 
                    var formData = new FormData(formElement),
                    convertedJSON = ;

                    formData.forEach(function(value, key)
                    convertedJSON[key] = value;
                    );

                    return convertedJSON;



                    Warning: this answer doesn't work in IE11.

                    FormData doesn't have a forEach method in IE11.

                    I'm still searching for a final solution to support all major browsers.






                    share|improve this answer






















                    • this is perfect! we have to support older browsers and the iterator use is not very intuitive.
                      – Peter Hawkins
                      Dec 4 '17 at 14:21












                    up vote
                    3
                    down vote










                    up vote
                    3
                    down vote









                    FormData method .entries and the for of expression is not supported in IE11 and Safari.



                    Here is a simplier version to support Safari, Chrome, Firefox and Edge



                    function formDataToJSON(formElement) 
                    var formData = new FormData(formElement),
                    convertedJSON = ;

                    formData.forEach(function(value, key)
                    convertedJSON[key] = value;
                    );

                    return convertedJSON;



                    Warning: this answer doesn't work in IE11.

                    FormData doesn't have a forEach method in IE11.

                    I'm still searching for a final solution to support all major browsers.






                    share|improve this answer














                    FormData method .entries and the for of expression is not supported in IE11 and Safari.



                    Here is a simplier version to support Safari, Chrome, Firefox and Edge



                    function formDataToJSON(formElement) 
                    var formData = new FormData(formElement),
                    convertedJSON = ;

                    formData.forEach(function(value, key)
                    convertedJSON[key] = value;
                    );

                    return convertedJSON;



                    Warning: this answer doesn't work in IE11.

                    FormData doesn't have a forEach method in IE11.

                    I'm still searching for a final solution to support all major browsers.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Dec 14 '17 at 13:56

























                    answered Sep 8 '17 at 11:45









                    Tomas Prado

                    2,10611629




                    2,10611629











                    • this is perfect! we have to support older browsers and the iterator use is not very intuitive.
                      – Peter Hawkins
                      Dec 4 '17 at 14:21
















                    • this is perfect! we have to support older browsers and the iterator use is not very intuitive.
                      – Peter Hawkins
                      Dec 4 '17 at 14:21















                    this is perfect! we have to support older browsers and the iterator use is not very intuitive.
                    – Peter Hawkins
                    Dec 4 '17 at 14:21




                    this is perfect! we have to support older browsers and the iterator use is not very intuitive.
                    – Peter Hawkins
                    Dec 4 '17 at 14:21










                    up vote
                    2
                    down vote













                    If you are using lodash it can be done concisely with fromPairs



                    import fromPairs from 'lodash';

                    const object = fromPairs(Array.from(formData.entries()));





                    share|improve this answer
























                      up vote
                      2
                      down vote













                      If you are using lodash it can be done concisely with fromPairs



                      import fromPairs from 'lodash';

                      const object = fromPairs(Array.from(formData.entries()));





                      share|improve this answer






















                        up vote
                        2
                        down vote










                        up vote
                        2
                        down vote









                        If you are using lodash it can be done concisely with fromPairs



                        import fromPairs from 'lodash';

                        const object = fromPairs(Array.from(formData.entries()));





                        share|improve this answer












                        If you are using lodash it can be done concisely with fromPairs



                        import fromPairs from 'lodash';

                        const object = fromPairs(Array.from(formData.entries()));






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jan 3 at 13:26









                        Erik van Velzen

                        2,98221512




                        2,98221512




















                            up vote
                            1
                            down vote













                            This post is already a year old... but, I really, really like the ES6 @dzuc answer. However it is incomplete by not been able to handle multiple selects or checkboxes. This has already pointed and code solutions has been offered. I find them heavy and not optimized. So I wrote a 2 versions based on @dzuc to handle these cases:



                            • For ASP style forms where multiple items name could just simple repeated.

                            let r=Array.from(fd.entries()).reduce(
                            (o , p) => (
                            (!o[p[0]])
                            ? ...o , [p[0]] : p[1]
                            : ...o , [p[0]] : [...o[p[0]] , p[1]]
                            )
                            ,
                            );
                            let obj=JSON.stringify(r);


                            One line Hotshot version:



                            Array.from(fd.entries()).reduce((o,p)=>((!o[p[0]])?...o,[p[0]]:p[1]:...o,[p[0]]:[...o[p[0]],p[1]]),);


                            • For PHP style forms where the multiple item names must have a suffix.

                            let r=Array.from(fd.entries()).reduce(
                            (o , p) => (
                            (p[0].split('[').length>1)
                            ? (p[0]=p[0].split('[')[0]
                            , (!o[p[0]])
                            ? ...o , [p[0]] : [p[1]]
                            : ...o , [p[0]] : [...o[p[0]] , p[1] ]
                            )
                            : ...o , [p[0]] : p[1]
                            )
                            ,
                            );
                            let obj=JSON.stringify(r);


                            One line Hotshot version:



                            Array.from(fd.entries()).reduce((o,p)=>((p[0].split('[').length>1)?(p[0]=p[0].split('[')[0],(!o[p[0]])?...o,[p[0]]:[p[1]]:...o,[p[0]]:[...o[p[0]],p[1]]):...o,[p[0]]:p[1]),);





                            share|improve this answer


























                              up vote
                              1
                              down vote













                              This post is already a year old... but, I really, really like the ES6 @dzuc answer. However it is incomplete by not been able to handle multiple selects or checkboxes. This has already pointed and code solutions has been offered. I find them heavy and not optimized. So I wrote a 2 versions based on @dzuc to handle these cases:



                              • For ASP style forms where multiple items name could just simple repeated.

                              let r=Array.from(fd.entries()).reduce(
                              (o , p) => (
                              (!o[p[0]])
                              ? ...o , [p[0]] : p[1]
                              : ...o , [p[0]] : [...o[p[0]] , p[1]]
                              )
                              ,
                              );
                              let obj=JSON.stringify(r);


                              One line Hotshot version:



                              Array.from(fd.entries()).reduce((o,p)=>((!o[p[0]])?...o,[p[0]]:p[1]:...o,[p[0]]:[...o[p[0]],p[1]]),);


                              • For PHP style forms where the multiple item names must have a suffix.

                              let r=Array.from(fd.entries()).reduce(
                              (o , p) => (
                              (p[0].split('[').length>1)
                              ? (p[0]=p[0].split('[')[0]
                              , (!o[p[0]])
                              ? ...o , [p[0]] : [p[1]]
                              : ...o , [p[0]] : [...o[p[0]] , p[1] ]
                              )
                              : ...o , [p[0]] : p[1]
                              )
                              ,
                              );
                              let obj=JSON.stringify(r);


                              One line Hotshot version:



                              Array.from(fd.entries()).reduce((o,p)=>((p[0].split('[').length>1)?(p[0]=p[0].split('[')[0],(!o[p[0]])?...o,[p[0]]:[p[1]]:...o,[p[0]]:[...o[p[0]],p[1]]):...o,[p[0]]:p[1]),);





                              share|improve this answer
























                                up vote
                                1
                                down vote










                                up vote
                                1
                                down vote









                                This post is already a year old... but, I really, really like the ES6 @dzuc answer. However it is incomplete by not been able to handle multiple selects or checkboxes. This has already pointed and code solutions has been offered. I find them heavy and not optimized. So I wrote a 2 versions based on @dzuc to handle these cases:



                                • For ASP style forms where multiple items name could just simple repeated.

                                let r=Array.from(fd.entries()).reduce(
                                (o , p) => (
                                (!o[p[0]])
                                ? ...o , [p[0]] : p[1]
                                : ...o , [p[0]] : [...o[p[0]] , p[1]]
                                )
                                ,
                                );
                                let obj=JSON.stringify(r);


                                One line Hotshot version:



                                Array.from(fd.entries()).reduce((o,p)=>((!o[p[0]])?...o,[p[0]]:p[1]:...o,[p[0]]:[...o[p[0]],p[1]]),);


                                • For PHP style forms where the multiple item names must have a suffix.

                                let r=Array.from(fd.entries()).reduce(
                                (o , p) => (
                                (p[0].split('[').length>1)
                                ? (p[0]=p[0].split('[')[0]
                                , (!o[p[0]])
                                ? ...o , [p[0]] : [p[1]]
                                : ...o , [p[0]] : [...o[p[0]] , p[1] ]
                                )
                                : ...o , [p[0]] : p[1]
                                )
                                ,
                                );
                                let obj=JSON.stringify(r);


                                One line Hotshot version:



                                Array.from(fd.entries()).reduce((o,p)=>((p[0].split('[').length>1)?(p[0]=p[0].split('[')[0],(!o[p[0]])?...o,[p[0]]:[p[1]]:...o,[p[0]]:[...o[p[0]],p[1]]):...o,[p[0]]:p[1]),);





                                share|improve this answer














                                This post is already a year old... but, I really, really like the ES6 @dzuc answer. However it is incomplete by not been able to handle multiple selects or checkboxes. This has already pointed and code solutions has been offered. I find them heavy and not optimized. So I wrote a 2 versions based on @dzuc to handle these cases:



                                • For ASP style forms where multiple items name could just simple repeated.

                                let r=Array.from(fd.entries()).reduce(
                                (o , p) => (
                                (!o[p[0]])
                                ? ...o , [p[0]] : p[1]
                                : ...o , [p[0]] : [...o[p[0]] , p[1]]
                                )
                                ,
                                );
                                let obj=JSON.stringify(r);


                                One line Hotshot version:



                                Array.from(fd.entries()).reduce((o,p)=>((!o[p[0]])?...o,[p[0]]:p[1]:...o,[p[0]]:[...o[p[0]],p[1]]),);


                                • For PHP style forms where the multiple item names must have a suffix.

                                let r=Array.from(fd.entries()).reduce(
                                (o , p) => (
                                (p[0].split('[').length>1)
                                ? (p[0]=p[0].split('[')[0]
                                , (!o[p[0]])
                                ? ...o , [p[0]] : [p[1]]
                                : ...o , [p[0]] : [...o[p[0]] , p[1] ]
                                )
                                : ...o , [p[0]] : p[1]
                                )
                                ,
                                );
                                let obj=JSON.stringify(r);


                                One line Hotshot version:



                                Array.from(fd.entries()).reduce((o,p)=>((p[0].split('[').length>1)?(p[0]=p[0].split('[')[0],(!o[p[0]])?...o,[p[0]]:[p[1]]:...o,[p[0]]:[...o[p[0]],p[1]]):...o,[p[0]]:p[1]),);






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Dec 6 at 1:29

























                                answered Nov 11 at 1:33









                                Carlos H.

                                1446




                                1446




















                                    up vote
                                    0
                                    down vote













                                    You can try this



                                    formDataToJSON($('#form_example'));

                                    # Create a function to convert the serialize and convert the form data
                                    # to JSON
                                    # @param : $('#form_example');
                                    # @return a JSON Stringify
                                    function formDataToJSON(form)
                                    let obj = ;
                                    let formData = form.serialize();
                                    let formArray = formData.split("&");

                                    for (inputData of formArray)
                                    let dataTmp = inputData.split('=');
                                    obj[dataTmp[0]] = dataTmp[1];

                                    return JSON.stringify(obj);






                                    share|improve this answer


























                                      up vote
                                      0
                                      down vote













                                      You can try this



                                      formDataToJSON($('#form_example'));

                                      # Create a function to convert the serialize and convert the form data
                                      # to JSON
                                      # @param : $('#form_example');
                                      # @return a JSON Stringify
                                      function formDataToJSON(form)
                                      let obj = ;
                                      let formData = form.serialize();
                                      let formArray = formData.split("&");

                                      for (inputData of formArray)
                                      let dataTmp = inputData.split('=');
                                      obj[dataTmp[0]] = dataTmp[1];

                                      return JSON.stringify(obj);






                                      share|improve this answer
























                                        up vote
                                        0
                                        down vote










                                        up vote
                                        0
                                        down vote









                                        You can try this



                                        formDataToJSON($('#form_example'));

                                        # Create a function to convert the serialize and convert the form data
                                        # to JSON
                                        # @param : $('#form_example');
                                        # @return a JSON Stringify
                                        function formDataToJSON(form)
                                        let obj = ;
                                        let formData = form.serialize();
                                        let formArray = formData.split("&");

                                        for (inputData of formArray)
                                        let dataTmp = inputData.split('=');
                                        obj[dataTmp[0]] = dataTmp[1];

                                        return JSON.stringify(obj);






                                        share|improve this answer














                                        You can try this



                                        formDataToJSON($('#form_example'));

                                        # Create a function to convert the serialize and convert the form data
                                        # to JSON
                                        # @param : $('#form_example');
                                        # @return a JSON Stringify
                                        function formDataToJSON(form)
                                        let obj = ;
                                        let formData = form.serialize();
                                        let formArray = formData.split("&");

                                        for (inputData of formArray)
                                        let dataTmp = inputData.split('=');
                                        obj[dataTmp[0]] = dataTmp[1];

                                        return JSON.stringify(obj);







                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Sep 17 at 4:18

























                                        answered Sep 17 at 4:08









                                        Ivan Fretes

                                        19826




                                        19826




















                                            up vote
                                            0
                                            down vote













                                            Even though the answer from @dzuc is already very good, you could use array destructuring (available in modern browsers or with Babel) to make it even a bit more elegant:



                                            // original version from @dzuc
                                            const data = Array.from(formData.entries())
                                            .reduce((memo, pair) => (
                                            ...memo,
                                            [pair[0]: pair[1],
                                            ), )

                                            // with array destructuring
                                            const data = Array.from(formData.entries())
                                            .reduce((memo,[key, value]) => (
                                            ...memo,
                                            [key]: value,
                                            ), )





                                            share|improve this answer
























                                              up vote
                                              0
                                              down vote













                                              Even though the answer from @dzuc is already very good, you could use array destructuring (available in modern browsers or with Babel) to make it even a bit more elegant:



                                              // original version from @dzuc
                                              const data = Array.from(formData.entries())
                                              .reduce((memo, pair) => (
                                              ...memo,
                                              [pair[0]: pair[1],
                                              ), )

                                              // with array destructuring
                                              const data = Array.from(formData.entries())
                                              .reduce((memo,[key, value]) => (
                                              ...memo,
                                              [key]: value,
                                              ), )





                                              share|improve this answer






















                                                up vote
                                                0
                                                down vote










                                                up vote
                                                0
                                                down vote









                                                Even though the answer from @dzuc is already very good, you could use array destructuring (available in modern browsers or with Babel) to make it even a bit more elegant:



                                                // original version from @dzuc
                                                const data = Array.from(formData.entries())
                                                .reduce((memo, pair) => (
                                                ...memo,
                                                [pair[0]: pair[1],
                                                ), )

                                                // with array destructuring
                                                const data = Array.from(formData.entries())
                                                .reduce((memo,[key, value]) => (
                                                ...memo,
                                                [key]: value,
                                                ), )





                                                share|improve this answer












                                                Even though the answer from @dzuc is already very good, you could use array destructuring (available in modern browsers or with Babel) to make it even a bit more elegant:



                                                // original version from @dzuc
                                                const data = Array.from(formData.entries())
                                                .reduce((memo, pair) => (
                                                ...memo,
                                                [pair[0]: pair[1],
                                                ), )

                                                // with array destructuring
                                                const data = Array.from(formData.entries())
                                                .reduce((memo,[key, value]) => (
                                                ...memo,
                                                [key]: value,
                                                ), )






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Dec 7 at 13:22









                                                Jerry

                                                1,6412127




                                                1,6412127



























                                                    draft saved

                                                    draft discarded
















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid


                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.

                                                    To learn more, see our tips on writing great answers.





                                                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                    Please pay close attention to the following guidance:


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid


                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.

                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function ()
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41431322%2fhow-to-convert-formdatahtml5-object-to-json%23new-answer', 'question_page');

                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    Darth Vader #20

                                                    How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

                                                    Ondo