views:

285

answers:

3

I'm using jQuery.

serialize seems not fit for this job.

A: 

You can call join() on your array to combine the elements into a string. And split() can be used to split a string into an array, with optional seperator and limit parameters.

Kaleb Brasee
and `split(',')` to reverse it (assuming no in-array strings used it).
LiraNuna
+1  A: 

It's not clear what you're looking for, if you just want the array represented as a string then you can call toString, which most types in javascript have defined:

>>> [1,2,3].toString()
"1,2,3"
thenduks
Can this process be reversed?
Yes, with `str.split();`
Jonathan Sampson
The array can be multi-dimensional.
No. `['x,y', 'z']` ⇒ `x,y,z` ⇒ `['x', 'y', 'z']`.
bobince
Good observation, bobince.
Jonathan Sampson
+1  A: 

The only serialisation on ‘arbitrary objects’ is toString as described by thenduks. This is a convenience serialisation for display purposes only (and even then very often generates useless string representations like [object Object]).

Can this process be reversed?

Not reliably, no.

If the datatypes you need to serialise are just the JS builtins like Array, String, Number and unprototyped Object being used as a transparent mapping, you can use JSON. Call JSON.stringify(obj) to serialise, JSON.parse(str) to re-parse. Use json2 or some other library with JSON features to support old browsers that don't have native JSON.

But ‘arbitrary objects’? No, can't be done (not in most other languages either).

bobince
I don't think it can't be done in most languages,because in PHP I can simply do it by $str = serialize($object); and $object = unserialize($str);
Not for ‘arbitrary objects’. There are unserialisable objects even for PHP.
bobince
OK,but in my case I just need it to work with multiple dimensional array.
OK great! JSON's fine, then.
bobince
But I'm already using jQuery,you mean I should pull another library?
Yes. It's a curious omission that jQuery has no JSON serialiser. (It can of course parse JSON just using `eval`.) See eg. http://stackoverflow.com/questions/191881/serializing-to-json-in-jquery
bobince
OK,I've decided to pull it in,thanks:)