Mark Mark - 5 months ago 42
Javascript Question

how to parse a serialized array to a jQuery array

I have a jQuery sortable list and I am serializing the result.

var data = $("#sortable").sortable('serialize');


The result looks like this:

item[]=41&item[]=49&item[]=51&item[]=35&item[]=58&item[]=45&item[]=32&item[]=36&item[]=26&item[]=27&item[]=33&item[]=31&item[]=29


Now I want to select each array index by using jQuery
$each
.

$.each(data, function(index, value ) {

alert( value );
});


And I will get the error:


TypeError: Cannot use 'in' operator to search for 'length' in item[]=51&item[]=41&item[]=49&item[]=35&item[]=58&item[]=45&item[]=32&item[]=36&item[]=26&item[]=27&item[]=33&item[]=31&item[]=29


So probably I have to parse it to an array using JSON.parse():

var data = $("#sortable").sortable('serialize');
data=JSON.parse(data);
$.each(data, function(index, value ) {
alert( value );
});


That will causes the error


VM327:1 Uncaught SyntaxError: Unexpected token i in JSON at position 0


So it might be the problem that JSON parser expects a string with
"
at the beginning and the ending.

var data = $("#sortable").sortable('serialize');
data=JSON.stringify(data);
data=JSON.parse(data);
$.each(data, function(index, value ) {
alert( value );
});


But this will lead to the first TypeError.

How can I parse a jQuery sortable object to a data array?

Answer

Use the "toArray" method instead of the "serialize" method.

var arr = $("#sortable").sortable('toArray');
$.each(arr, function(index, value) {
    alert(value);
});

BTW, a String of the following form is not JSON. In fact, it is not even close to JSON.

item[]=51&item[]=41&item[]=49&item[]=35&item[]=58&item[]=45&item[]=32&item[]=36&item[]=26&item[]=27&item[]=33&item[]=31&item[]=29

A JSON string for an array would look like:

[51, 41, 49, 35, 58, 45, 32, 36, 26, 27, 33, 31, 29]