convert form data to json in javascript

How to Convert Form Data to JSON in JavaScript

FormData objects are used to capture form data elements as a set of key-value pairs so that you can easily send them to the web server or other locations. It is basically an array-like iterable structure that contains key-value pairs of HTML form. In this article, we will learn how to convert Form data to JSON in JavaScript, so that you can easily send it to your web server. We will not serialize the entire form data but only its key value pairs.


How to Convert Form Data to JSON in JavaScript

Let us say you have the following HTML form.

<form id="formElem">
  <input type="text" name="name" value="John">
  <input type="text" name="surname" value="Smith">
  <input type="submit">
</form>

Here is the code to get formData object for this form.

var formData = new FormData(formElem);

Let us say you want to capture the key-value pairs in this form. You can easily do it using forEach() function to loop through the key-value pairs in form data object, and storing the key-value pairs in a JavaScript object. It is available for each Form Data object in JavaScript.

var object = {};
formData.forEach(function(value, key){
    object[key] = value;
});

Once you have created the JavaScript object, you can use JSON library to serialize it.

var json = JSON.stringify(object);

Putting together everything,

var formData = new FormData(formElem);
var object = {};
formData.forEach(function(value, key){
    object[key] = value;
});
var json = JSON.stringify(object);

The above code works when each form element accepts only a single value, such as text box, radio buttons, etc. If your form elements accept multiple values, such as multiselect dropdowns, then you need to modify the above code as shown below.

var object = {};
formData.forEach((value, key) => {
    // Reflect.has in favor of: object.hasOwnProperty(key)
    if(!Reflect.has(object, key)){
        object[key] = value;
        return;
    }
    if(!Array.isArray(object[key])){
        object[key] = [object[key]];    
    }
    object[key].push(value);
});
var json = JSON.stringify(object);

In the above code, we use built-in Reflect object that allows you to easily make objects reflect into themselves, that is, evaluate themselves during iteration. While we loop through each key-value pair in form data, we use this to check if an object has key present in it. If there is no key present, we simply store the key-value pair in object and return. If there is a key-value pair, we check if it is an array or not. If it is not an array, we set it to be an array with the value as its first element. We store the subsequent values (for multiple values) of form element as array items, one after the other.

Please note, if you want to send form data to web server through XML HTTP request, you can directly send form data object without converting it into JSON, as shown below.

var request = new XMLHttpRequest();
request.open("POST", "http://example.com/submitform.php");
request.send(formData);

In this article, we have learnt how to convert form data to JSON.

Also read:

How to Check if Element is Visible After Scrolling
How to Use Variable in Regex in JavaScript
How to Use Variable in Regex in Python
How to Split Array into Chunks in JavaScript
How to Print Number With Commas As Thousands Separator

Leave a Reply

Your email address will not be published. Required fields are marked *