3

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.

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm not too sure about JSON.stringify since my objects contain methods, and last time I checked it would give me a TypeError :/ see this for instance : jsfiddle.net/cyddle/49fdu the function is not stringified
@Downvoter, may I ask why? My answer is the same as the other three answers, just with more detail. It happens to be the accepted answer as well. Why the downvote?
1

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.

Comments

0

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.

1 Comment

nothing is on the server so far, this is a 100% HTML5/JS project, so I can pick anything. I have no way to predict the size of the final array to store, so I guess my table will to consist in an ID and a huuuuge blob ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.