12

So in javascript I have an array that looks about like this:

[{x1:0,x2:2000,y:300},{x1:50,x2:250,y:500}]

And I would like to store it in a single field in my database. I thought about either somehow making it a string and then saving it as text, but I don't really know a very efficient and "smart" way to do that. I also heard of the VARBINARY field type, but I have no idea how to write and object/array into one of those and how to read it out...

What I would really most prefer would be if it would automatically be read as an array. My MYSQL-plugin(or however that is called in js) returns my queries as arrays of objects like well:

[{id:0,bla:"text"},{id:0,bla:"text"}]

For a query in a table with the collumns id and bla.

Well say my array is stored in bla, I would like the object I get to look exactly like this right when it is returned(however if that is not possible I am fine with an alternative solution).

[{id:0,bla:[{x1:0,x2:2000,y:300},{x1:50,x2:250,y:500}]},{id:0,bla:[{x1:0,x2:2000,y:300},{x1:50,x2:250,y:500}]}]

So basically I would get an array containing two objects, which each have the properties bla and id, where bla is an array of objects with the properties x1,x2 and y.

Wingblade
  • 9,585
  • 10
  • 35
  • 48

1 Answers1

19

somehow making it a string and then saving it as text, but I don't really know a very efficient and "smart" way to do that.

Save the string as JSON, like this:

var myArr = [{x1:0,x2:2000,y:300},{x1:50,x2:250,y:500}];
myArrString = JSON.stringify(myArr);

Later, when you get the JSON string back from MySQL, you can turn it back into an array with JSON.parse(), like this:

var myArr = JSON.parse(myArrString)

And yes, if you're wondering, JSON functionality has been added to Javascript's standard codebase: that's how popular it is.

Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
  • Had never looked into this JSON much before, but it seems interesting so I guess I could give it a try... – Wingblade May 10 '12 at 18:29
  • It's so simple, I've already told you all you need to know. :) – Elliot Bonneville May 10 '12 at 18:30
  • That's really everything? So JSON only has the two functions JSON.stringify() and JSON.parse()? Nice and simple, just how I like it. – Wingblade May 10 '12 at 18:34
  • 1
    Yep, that's it. Incredibly simple, but incredibly useful. You can also define your own packing and unpacking procedures for complicated objects that don't want to pack nicely, but for simple stuff like you're doing here, `stringify` and `parse` should work nicely. – Elliot Bonneville May 10 '12 at 19:29