Home >Web Front-end >JS Tutorial >How to Convert HTML5 FormData to JSON Without Serialization?

How to Convert HTML5 FormData to JSON Without Serialization?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 14:26:02316browse

How to Convert HTML5 FormData to JSON Without Serialization?

Converting HTML5 FormData to JSON without Serialization

When working with HTML5 forms, there may arise a need to convert the form's data to JSON. One common approach is to serialize the FormData object; however, this may not be desirable in all cases. Here's how you can convert FormData entries to JSON without serialization:

Step 1: Iterate over the FormData Object

Use the forEach() method to iterate over the FormData object's entries. Each entry contains a key (field name) and a value (input value).

Step 2: Create a Plain Object

Initialize an empty object to store the converted JSON data.

Step 3: Convert Entries to Key-Value Pairs

Within the forEach() callback, assign the values to the object based on their keys. For example:

<code class="javascript">formData.forEach(function(value, key) {
    object[key] = value;
});</code>

Step 4: Convert Object to JSON

Finally, use the JSON.stringify() method to convert the object into a JSON string.

<code class="javascript">var json = JSON.stringify(object);</code>

Using ES6 Arrow Functions

You can simplify the forEach() loop using ES6 arrow functions:

<code class="javascript">formData.forEach((value, key) => object[key] = value);</code>

Supporting Multiple Values

If your form includes fields with multiple values, such as multi-select lists, you can modify the above code to support them:

<code class="javascript">formData.forEach((value, key) => {
    if (!Array.isArray(object[key])) {
        object[key] = [object[key]];
    }
    object[key].push(value);
});</code>

Sending FormData Directly

If your goal is to submit the form data via an XMLHttpRequest, you can consider sending the FormData object directly without converting it to JSON. This approach is also supported by the Fetch API.

Handling Complex Objects

Note that the JSON.stringify() method may encounter limitations when dealing with complex objects. In such cases, consider defining a toJSON() method within your objects to specify custom serialization logic.

The above is the detailed content of How to Convert HTML5 FormData to JSON Without Serialization?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn