1

I'm using jQuery.

serialize seems not fit for this job.

2
  • 2
    Serialize to what? XML, JSON, CSV, etc..
    – gn22
    Dec 8, 2009 at 4:12
  • 1
    From an arbitrary object to string
    – user198729
    Dec 8, 2009 at 4:17

3 Answers 3

2

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).

5
  • 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);
    – user198729
    Dec 8, 2009 at 4:34
  • Not for ‘arbitrary objects’. There are unserialisable objects even for PHP.
    – bobince
    Dec 8, 2009 at 4:37
  • OK,but in my case I just need it to work with multiple dimensional array.
    – user198729
    Dec 8, 2009 at 4:39
  • 1
    But I'm already using jQuery,you mean I should pull another library?
    – user198729
    Dec 8, 2009 at 4:43
  • Yes. It's a curious omission that jQuery has no JSON serialiser. (It can of course parse JSON just using eval.) See eg. stackoverflow.com/questions/191881/…
    – bobince
    Dec 8, 2009 at 5:06
1

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"
3
  • Can this process be reversed?
    – user198729
    Dec 8, 2009 at 4:20
  • The array can be multi-dimensional.
    – user198729
    Dec 8, 2009 at 4:32
  • 2
    No. ['x,y', 'z']x,y,z['x', 'y', 'z'].
    – bobince
    Dec 8, 2009 at 4:32
0

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.

1
  • and split(',') to reverse it (assuming no in-array strings used it).
    – LiraNuna
    Dec 8, 2009 at 4:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.