Storing a javascript array that contains objects in a MYSQL database?

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.


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.

链接地址: http://www.djcxy.com/p/47830.html

上一篇: .net中的json有什么用处

下一篇: 存储包含MYSQL数据库中的对象的JavaScript数组?