最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Storing JS arrays and objects in a database - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Nov 1, 2011 at 12:24 CystackCystack 3,5716 gold badges36 silver badges35 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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.

If you have no interest in quering the objects for their various properties but only persist them to save state, you can serialize the entire array to JSON and store it in any db you like as one string.

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.

发布评论

评论列表(0)

  1. 暂无评论