Steve Steve - 1 year ago 53
Javascript Question

Custom object to JSON then back to a custom object?

I've seen very similar questions to this, but I can't quite decide if they was answered clearly - maybe I'm being a bit dense, sorry.

I want to have the convenience (and clarity) of my own object, call it a

. It won't contain code, just data. I want to write this to a database and read it back later, but obviously, it is a type
when it's read back. All I can think of to find out what it used to be is:

  1. Have a member variable
    that I set to CARDBOARD_BOX

  2. Instantiate a new
    and use a function (in the box) to copy the properties of
    to the new

Is there a better way of doing this? I'm pretty sure I can change the actual type.

function CardboardBox() {
this.type = "CARDBOARD_BOX" = "No set";
this.populate = new function(obj) {
// populate this object with obj properties

var box = new CarboardBox(); // CarboardBox = "My Box";
send = JSON.stringyfy(box);
obj = JSON.parse(send); // Object

if (obj.type == "CARDBOARD_BOX") {
savedBox = new CardboardBox();

Thanks in advance...

[edit] My test code.

function CardboardBox(n) { = n;

var box = new CardboardBox("My Box");
send = JSON.stringify(box); // JSON CarboardBox()

obj = JSON.parse(send, function fn(obj) { // Object() returned
log("OB: "+obj.type);
return obj.type === 'CardboardBox' ? new CardboardBox(obj) : CardboardBox;

Output is:

OB: undefined utils.js:40
OB: undefined utils.js:40
function CardboardBox(n) { = n;

Answer Source

One possible solution is the following:

function CardboardBox(n) {
  if(typeof(n) == 'string') {
    //build from name string = n;
  } else {
    //build from object =;

  //add in this object's "type" in a place
  //that is unlikely to exist in other JSON strings
  this.__type = 'CardboardBox';

var box = new CardboardBox("My Box");
send = JSON.stringify(box), // JSON CarboardBox()
obj = JSON.parse(send, function(key, val) {
  //if this is an object, and is CardboardBox
  if(typeof(val) === 'object' && val.__type === 'CardboardBox')
      return new CardboardBox(val);

  return val;

  //or if your object is in a context (like window), and there are many of
  //them that could be in there, you can do:
  //if(typeof(val) === 'object' && context[val.__type])
  //    return new context[val.__type](val);


Basically store the object type in a place you know to look for later on when parsing the json. if you have multiple objects you can instantiate in a single scope the second parse method may be more appropriate. This also will account for objects in the JSON that are not CarboardBoxs.

Edit Here is a jsFiddle of this method in action.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download