Skip to content

Instantly share code, notes, and snippets.

@kieranbarker
Last active May 25, 2023 11:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kieranbarker/98f8dadbf824236e42820419b1da58eb to your computer and use it in GitHub Desktop.
Save kieranbarker/98f8dadbf824236e42820419b1da58eb to your computer and use it in GitHub Desktop.
Serialize all form data into a JSON string
/**
* Serialize all form data into a JSON string.
* https://gist.github.com/kieranbarker/98f8dadbf824236e42820419b1da58eb
* @param {HTMLFormElement} form The form to serialize.
* @returns {string} The serialized form data.
*/
function serializeJSON (form) {
// Create a new FormData object
const formData = new FormData(form);
// Create an object to hold the name/value pairs
const pairs = {};
// Add each name/value pair to the object
for (const [name, value] of formData) {
pairs[name] = value;
}
// Return the JSON string
return JSON.stringify(pairs);
}
@kieranbarker
Copy link
Author

@kieranbarker
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment