Reputation: 34934
I have a method which sends an ajax request. When the reply from the server is received I need to serialize and later de-serialize
$.ajax({
//.....
done(function(data) {
//1 Need to serialize data (which is an array)
});
function myFunction() {
//2 Need to de-serialize data which has been serialized
}
I know I could use jquery#serializeArray()
if I had a form to serialize:
$( "form" ).submit(function( event ) {
console.log( $( this ).serializeArray() );
event.preventDefault();
});
But I don't have a form and data from the server (I guess) has nothing to do with serializeArray
function of jquery
. So how can I do it? What's one of the best ways?
Preferably not to use any third-party libraries except jquery or even not to use jquery at all.
Upvotes: 0
Views: 3131
Reputation: 5676
The common way to serialize JS-objects to JSON is via JSON.stringify()
.
The other way around is via JSON.parse()
.
o={"firstName":"john","lastName":"doe"};
console.log(JSON.stringify(o));
console.log(JSON.parse(JSON.stringify(o)));
See MDN for stringify and parse
Here is a Fiddle.
.serializeArray() from jQuery is only a neat helper function to serialize form-data.
It builds its objects from the ground up. Here is the source for that.
If you want to submit your data as JSON
, you simply
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
success: success,
dataType: dataType
});
Free after jQuery.post().
Upvotes: 1