Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing and unserializing an array in javascript

I'm using the tag-it library for jquery to make a tagging system (a bit like the stackoverflow one).

After the user types his tags the library returns a javascript array that I want to save in a MySQL database. I didn't find a serialize and unserialize function in javascript.

Before coding my own function I'd like to make sure I'm not reinventing the wheel here. It seems crazy that there is no native way to save an array to a database and then use it again.

tl;dr => how can I save a javascript array in a MySQL database to reuse it later ?

like image 612
Lukmo Avatar asked Jul 03 '12 13:07

Lukmo


3 Answers

You can use JSON.stringify() (MDN docu) and JSON.parse() (MDN docu) for converting a JavaScript object into a string representation to store it inside a database.

var arr = [ 1, 2, 3 ];  var serializedArr = JSON.stringify( arr ); // "[1, 2, 3]"  var unpackArr = JSON.parse( serializedArr ); // identical array to arr 

If your backend is written in PHP, there are similar methods to work with JSON strings there: json_encode() (PHP docu) and json_decode() (PHP docu).

Most other languages offer similar functionalities for JSON strings.

like image 109
Sirko Avatar answered Sep 21 '22 23:09

Sirko


You can use JavaScript Object Notation(JSON) format.

Javascript supports these methods:

  • JSON.stringify -> serializes object to string

  • JSON.parse -> deserializes object from string

like image 35
Engineer Avatar answered Sep 23 '22 23:09

Engineer


How about just JSONing it?

var arr = [1,2,3];
var arrSerialized = JSON.stringify(arr);
...

var arrExtracted = JSON.parse(arrSerialized);

By the way, JSON is often used for serializing in some other languages, even though they have their own serializing functions. )

like image 44
raina77ow Avatar answered Sep 25 '22 23:09

raina77ow