Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 CardboardBox(). 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 Object() when it's read back. All I can think of to find out what it used to be is:

  1. Have a member variable type that I set to CARDBOARD_BOX
  2. Instantiate a new CarbardBox() and use a function (in the box) to copy the properties of Object() to the new CardboardBox() object

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

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

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

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

Thanks in advance... Steve

[edit] My test code.

function CardboardBox(n) {
  this.name = 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; 
});     
console.log(obj);

Output is:

OB: undefined utils.js:40
OB: undefined utils.js:40
function CardboardBox(n) {
    this.name = n;
} 
like image 501
Steve Avatar asked Oct 19 '12 13:10

Steve


People also ask

How do I convert a JSON file to an object?

Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON.

How do you deserialize JSON to custom class objects in Python?

To deserialize the string to a class object, you need to write a custom method to construct the object. You can add a static method to ImageLabelCollection inside of which you construct Label objects from the loaded JSON dictionary and then assign them as a list to the class variable bbox.

Can you have a JSON object in a JSON object?

JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be valid JSON.

What is toJSON () in JSON?

if you need to read or clone all of a model's data attributes, use its toJSON() method. This method returns a copy of the attributes as an object (not a JSON string despite its name). (When JSON.


1 Answers

One possible solution is the following:

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

  //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);
});


console.log(obj);

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.

like image 86
Chad Avatar answered Sep 29 '22 13:09

Chad