2

I'm looking for the most up-to-date way to serialize an array of data in Javascript (w/ or w/o jQuery). Using the latest version of the Chrome browser (June 2013).

Simple associative array, PHP using serialize().

array('product_id' => "145549", "field" => "price")

-- serializes to --

a:2:{s:10:"product_id";s:6:"145549";s:5:"field";s:5:"price";}

If there's no easy way to produce the same serialized string using Javascript, is there an equivalent to PHP's json_encode()?

Dave Chen
  • 10,887
  • 8
  • 39
  • 67
jjwdesign
  • 3,272
  • 8
  • 41
  • 66
  • use `phpjs`, you can use all php kind of function in javascript. – Yogesh Suthar Jun 23 '13 at 05:38
  • 2
    That PHP's serialisation format kinda looks a bit like JSON except a little bloated up. Stick to JSON – John Dvorak Jun 23 '13 at 05:42
  • 1
    Serialization is for communication with different languages. AFAIK, PHP's serialization only allows communication with itself. It's highly recommend -- if you want to send data to javascript, to use JSON. – Dave Chen Jun 23 '13 at 05:46
  • 2
    we'd be able to help more if you provided why/what you are trying to accomplish. It's all about using the right tool for the job. – Brombomb Jun 23 '13 at 05:46
  • @Brombomb: I think I can rewrite my code to use json_encode() in PHP and JSON.stringify() in JavaScript. I was just hoping to avoid the rewrite of the serialize PHP code. BTW, the data is being sent from PHP or Javascript to a PHP backend method. – jjwdesign Jun 23 '13 at 06:33

1 Answers1

2

To elaborate on what Musa said in a comment. Most modern browsers supply a JSON object. You can use object detection to see if it is available. No jQuery required even if the browser does not have it you can supply it yourself, here.

Native support: SO Thread, even has some nice code examples.

Community
  • 1
  • 1
John
  • 1,530
  • 1
  • 10
  • 19