How to convert FormData (HTML5 object) to JSON
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);
UPDATE:
And for those who prefer the same solution with ES6 arrow functions:
var object = {};
formData.forEach((value, key) => object[key] = value);
var json = JSON.stringify(object);
UPDATE 2:And for those who want support for multi select lists or other form elements with multiple values (since there are so many comments below the answer regarding this issue I will add a possible solution):
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);
Here a Fiddle demonstrating the use of this method with a simple multi select list.
UPDATE 3:As a side note for those ending up here, in case the purpose of converting the form data to json is to send it through a XML HTTP request to a server you can send the FormData
object directly without converting it. As simple as this:
var request = new XMLHttpRequest();
request.open("POST", "http://example.com/submitform.php");
request.send(formData);
See also Using FormData Objects on MDN for reference:
UPDATE 4:As mentioned in one of the comments below my answer the JSON stringify
method won't work out of the box for all types of objects. For more information on what types are supported I would like to refer to the Description section in the MDN documentation of JSON.stringify
.
In the description is also mentioned that:
If the value has a toJSON() method, it's responsible to define what data will be serialized.
This means that you can supply your own toJSON
serialization method with logic for serializing your custom objects. Like that you can quickly and easily build serialization support for more complex object trees.
Convert form data to JSON object
I added above form in JSFiddle and it displays JSON data as output.
Working JSFiddle
$(function() {
$('form').submit(function() {
$('#result').text(JSON.stringify($('form').serializeObject()));
return false;
});
});
Convert json object to formData (HTML5 Object)
Try stringifying the javascript object to json.
formdata.append('file', JSON.stringify(uploadJson));
Note that JSON is a string data format and there is no such thing as a JSON object
Axios POST Form data as JSON
You apparently have two options ahead:
- You can use
v-model
for form input binding:
<form name="form" >
<input type="text" placeholder="Name" v-model="name" size="60"/></div>
<input type="text" placeholder="Surname" v-model="surname" size="60"/></div>
<input type="submit" value="Save" @click="getPostsViaREST"/>
</form>
And you can use them to build a json object when sending data:
methods: {
getPostsViaREST() {
// No form data, but json here
var user = {
// name and surname should exist in [data] or [computed] section
name: this.name,
surname: this.surname
};
axios.post("/users", user)
.then(response => {
this.getViaREST()
})
},
- Or you can keep your code and change the backend to accept form data: You cannot dictate the backend to accept certain types through a client request.
How to send a JSON object using html form data
Get complete form data as array and json stringify it.
var formData = JSON.stringify($("#myForm").serializeArray());
You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it. You'll then get all data in an array.
$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json"
});
Related Topics
How to Read a Properties File in JavaScript from Project Directory
How to Trigger Change of Option in Dropdown When Options Can Have Same Value
How to Create Line Breaks in Console.Log() in Node.Js
How to Get Public User All Posts from Instagram, Without Instagram API
Passing Variable from One Js to Another Js File in Nodejs
Remove the Default Browser Header and Footer When Printing HTML
Blocking Device Rotation on Mobile Web Pages
How to Run HTML File on Localhost
How to Mock Private Functions With Jest
How to Use Document.Getelementbyid() Method in Typescript
How to Check a Radio Button in the Table Row Based on That Column Header
How to Enable Scrolling on Website That Disabled Scrolling
Typeerror: Data.Foreach Is Not a Function
React - How to Add Dynamic Key/Value Pair to an Object
Loading Screen Gets Stuck While Processing Http Request
Onclick Button Get from Database and Display on a Input Field Live