Skip to content
the poor coder

how take values from JSON.stringify($('form').serialize())

Poor Man
Published
Reading time
1 min read
On this page

How to take values from JSON.stringify($('form').serialize())#

If you want to collect form data and turn it into a JSON string, you can use the jQuery serialize method and then JSON.stringify it.

Method 1:#

First, use jQuery to select the form element and serialize it into a string:

Text
var formdata = $('form').serialize();

Then, use JSON.stringify to turn it into a JSON string:

Text
var jsondata = JSON.stringify(formdata);

You can then output the JSON string to a div element:

Text
<div id="output"></div>

In your JavaScript, select the output div and set its text to the JSON string:

Text
$('#output').text(jsondata);

Method 2:#

A more concise way to achieve this is to combine the two steps into one using jQuery's map function:

Text
var formdata = $('form').serializeArray();
var jsondata = JSON.stringify($.map(formdata, function(obj){return {[obj.name]: obj.value}}));

This code first serializes the form data into an array using serializeArray. Then, it uses jQuery's map function to map each element of the array into an object with the element's name as the key and its value as the value. Finally, it JSON stringifies the resulting array of objects.

The outputting process is the same as in Method 1.

Method 3:#

If you want to use plain JavaScript instead of jQuery, you can use the FormData object:

Text
var formdata = new FormData(document.querySelector('form'));
var jsondata = {};
for (var pair of formdata.entries()) {
  jsondata[pair[0]] = pair[1];
}
jsondata = JSON.stringify(jsondata);

This code creates a new FormData object from the form element, and then iterates through its entries to construct a JSON object. Finally, it JSON stringifies the object.

The outputting process is the same as in Method 1.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC