html5 json表单,javascript - How to convert FormData (HTML5 object) to JSON - Stack Overflow
时间: 2024-03-05 19:50:42 浏览: 31
To convert FormData (HTML5 object) to JSON, you can use the following code:
```
function formDataToJson(formData) {
let json = {};
formData.forEach((value, key) => {
if (!json[key]) {
json[key] = value;
return;
}
if (Array.isArray(json[key])) {
json[key].push(value);
return;
}
json[key] = [json[key], value];
});
return JSON.stringify(json);
}
```
This function converts FormData to a JSON object. If the FormData object has multiple values for the same key, the function converts them to an array in the JSON object. You can call this function by passing the FormData object as an argument.
Note that the above code assumes that all values in the FormData object are strings. If your FormData object contains other data types, you may need to modify the code accordingly.
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)