35

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 ?

Lukmo
  • 1,688
  • 5
  • 20
  • 31
  • 1
    How about JSON? It depends on how you want to save it; do you really want a single row in the database for all the tags, or do you want separate rows? Seems like it'd be much easier to search by tag if the tags were separated into distinct rows. – Pointy Jul 03 '12 at 13:33
  • It seems to be the best way to do it. Thanks. – Lukmo Jul 03 '12 at 13:35
  • OK, well like I said, searching by tag is going to be much, much slower if the query has to dig through a string of tags stuffed into a single column. – Pointy Jul 03 '12 at 13:39
  • Problem is I want a dynamic number of tags, so I can't use separate rows since a crazy user could want 30 tags for one entry. – Lukmo Jul 03 '12 at 13:44
  • 1
    ??? Just have a table with a column for the primary key and a column for the tag. Then you can have as many tags as you want. That's a pretty common database pattern. – Pointy Jul 03 '12 at 14:12

3 Answers3

66

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.

Sirko
  • 72,589
  • 19
  • 149
  • 183
  • 1
    I just want to point out that JSON.parse will clean up the serialized output from a Web Api call that uses Newtonsoft.Json.JsonConvert.SerializeObject. In my case, I had a serialized string that looked like "["Industry","Region","Topic","Type"]", and JSON.parse converted it into the desired array of strings. – devinbost Sep 24 '14 at 09:32
  • This is Simple and Precise Solution :D – deva11 Apr 19 '18 at 12:31
8

You can use JavaScript Object Notation(JSON) format.

Javascript supports these methods:

Engineer
  • 47,849
  • 12
  • 88
  • 91
5

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

raina77ow
  • 103,633
  • 15
  • 192
  • 229