在数据库中存储JS数组和对象 [英] Storing JS arrays and objects in a database
问题描述
我有一个应用程序,允许用户使用JS构建内容。我希望用户能够保存其工作的当前状态以重复使用或共享,但是他所拥有的是存储在JS数组中的JS对象的集合,这些对象具有非常不同的属性(颜色,标签,x / y
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对于该特定任务来说似乎很糟糕,迫使我维护每个不同对象的表,可惜我对NoSQL数据库知之甚少。您将使用什么工具来执行此操作? MongoDB听起来很有前途,但是在我学习一种全新的数据库范例之前,我想确保我朝着正确的方向前进。
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.
推荐答案
对象到字符串:
您可以将对象作为JSON字符串存储在数据库中。这是一个简单的示例:
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);
这里是工作中的小提琴。
字符串到对象:
要将字符串转换回对象,只需调用 window.JSON.parse()
:
To convert your string back to an object, simply call window.JSON.parse()
:
var myObject = window.JSON.parse(stringRepresentation);
这里是工作中的小提琴。
这篇关于在数据库中存储JS数组和对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!