I want to serialize and un-serialize a form with jQuery.
How can I get all attributes of all elements in a serialized way?
.serialize() will map your input controls that have a name attribute defined into a standard query string:
foo=bar&bar=foo&and=soon
That kind of string is easy accesible in almost every "backend" programming language.
If you need to serialize object information, use JSON
.
var obj = {
foo: 'bar',
more: 'etc
};
serialize this with window.JSON.stringify(obj);
. To unserialize such a JSON string, use window.JSON.parse(str);
, which returns a javascript object.
Many languages support this principle.
serialize()
Is included in jQuery itself for this very purpose https://api.jquery.com/serialize/
$('#someKind .ofASelectorForYour form').serialize();
(returns serialized string)
unserialize()
Is not included in jQuery, but, the documentation says
The .serialize() method creates a text string in standard URL-encoded notation.
...so, in 2020, we can leverage the URLSearchParams
interface:
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
https://url.spec.whatwg.org/#interface-urlsearchparams
function unserialize(serializedData) {
let urlParams = new URLSearchParams(serializedData); // get interface / iterator
let unserializedData = {}; // prepare result object
for (let [key, value] of urlParams) { // get pair > extract it to key/value
unserializedData[key] = value;
}
return unserializedData;
}
(returns object of unserialized key => value pairs)
A one-liner for one-time usage extractor (your data in sData
, result in unsData
):
let prms = new URLSearchParams(sData); let unsData = {}; for (let [k, v] of prms) unsData[k] = v;
BTW: as MDN docs say,
following two lines are equivalent:
for (const [key, value] of mySearchParams) {}
for (const [key, value] of mySearchParams.entries()) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With