Say I have something like:
var obj = {id: 1, name: "Some name", color: "#444444" };
I want to serialize that object. I tried:
$(obj).serialize();
but that didn't work.
Any ideas?
The serialize() method is an inbuilt method in jQuery which is used to create a text string in standard URL-encoded notation. This method can act on a jQuery object that has selected individual form controls, such as input, textarea etc. Syntax: $(selector).serialize()
To get value from serialized array, use th serializeArray( ) method. The serializeArray( ) method serializes all forms and form elements like the . serialize() method but returns a JSON data structure for you to work with.
The process whereby an object or data structure is translated into a format suitable for transfer over a network, or storage (e.g. in an array buffer or file format). In JavaScript, for example, you can serialize an object to a JSON string by calling the function JSON. stringify() .
In computing, serialization (US and Oxford spelling) or serialisation (UK spelling) is the process of translating a data structure or object state into a format that can be stored (for example, in a file or memory data buffer) or transmitted (for example, over a computer network) and reconstructed later (possibly in a ...
You should use jQuery.param()
instead.
With vanilla JS, you would use JSON.stringify
instead.
As mentioned you should use .param()
$.param({id: 1, name: "Some name", color: '#444444' })
But also you need to be careful with your syntax. Your brackets don't match, and that color will need quotation marks. jsFiddle
You could use JSON.stringify
to serialize your object, and you'd have to wrap your color string correctly:
var obj = {id: 1, name: "Some name", color: '#444444' };
var serialized = JSON.stringify(obj);
// => "{"id":1,"name":"Some name","color":"#444444"}"
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