Saving javascript array containing objects in MYSQL database?

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

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

And I would like to save it in one field in my database. I thought about somehow making it a string and then saving it as text, but I really don't know a very effective and β€œsmart” way to do this. I also heard about the type of the VARBINARY field, but I have no idea how to write and create an object / array in one of them and how to read it ...

I would prefer it if it were automatically read as an array. My MYSQL plugin (or, however, is called in js) returns my queries as arrays of such objects, as well:

[{ID: 0, blah: "text"}, {ID: 0, blah: "text"}]

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

It is good that my array is stored in bla, I would like the object that I received to look exactly the same as when it was returned (however, if this is not possible, I am fine with an alternative solution).

[{ID: 0, blah: [{x1: 0, x2: 2000, Y: 300}, {x1: 50, x2: 250, Y: 500}]}, {ID: 0, blah: [{x1: 0, x2: 2000, Y: 300}, {x1: 50, x2: 250, Y: 500}]}]

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

+5
source share
1 answer

somehow creating a string and then saving it as text, but I really don’t know a very effective and β€œsmart” way to do this.

Save the string as JSON, for example:

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

, JSON MySQL, JSON.parse(), :

var myArr = JSON.parse(myArrString)

, , JSON ​​ Javascript: .

+10

All Articles