简体   繁体   中英

Storing JS arrays and objects in a database

I have an application that lets users build things in JS. I want the user to be able to save the current state of his work to reuse it or share it, but what he has is a collection of JS objects stored in a JS array, with very different properties (color, label, x/y position, size, etc.).

SQL seems terrible for that particular task, forcing me to maintain tables for every different object, and alas I know very little about NoSQL database. What tools would you use to perform this ? MongoDB sounds promising but before I learn a whole new DB paradigm I want to be sure that I am heading in the right direction.

Object to string:

You can store your objects in the DB as a JSON string. Here's a simple example:

var foo = new Object();
foo.Name = "James";
foo.Gender = "Male";

//Result: {"Name":"James","Gender":"Male"}
var stringRepresentation = window.JSON.stringify(foo);

Here's a working fiddle .

String to object:

To convert your string back to an object, simply call window.JSON.parse() :

var myObject = window.JSON.parse(stringRepresentation);

Here's a working fiddle .

如果您没有兴趣查询对象的各种属性,但只保留它们以保存状态,您可以将整个数组序列化为JSON并将其存储在您喜欢的任何数据库中作为一个字符串。

What's on the server?

Most languages have mature JSON implementations that convert JavaScript objects to native types, which you can then easily store in a SQL database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM