I have seen examples of how to do this that rely heavily on the browser environment but not examples that work in the native node.js environment.
I need to cast JSON objects to javascript classes of a type that does not yet exist but is given by an input string.
I found some nice code on stackoverflow to retype JSON to known class but I have not figured out how to do this when the class type is a string and the class does not exist.
In software terms I need to:
var className = 'Bar';
console.log(global[className]); // false - class Bar is not defined
var jsonIn = '{ "name": "Jason" }';
var retypedJson = retypeJSON(jsonIn, className);
console.log(retypedJson instanceof Bar) // true
The code for recasting JSON. (Nice as it doesn't call eval or explicitly copy property names.)
// define a class
var Foo = function(name) {
this.name = name;
}
// make a method
Foo.prototype.shout = function() {
console.log("I am " + this.name);
}
// make a simple object from JSON:
var x = JSON.parse('{ "name": "Jason" }');
// force its class to be Foo
x.__proto__ = Foo.prototype;
// the method works
x.shout();
console.log(x instanceof Foo); // true
Thanks!
I have an answer that makes some use of eval and __proto__. Eval is only used to create the first prototype.
// create prototype - called once
var on = 'Apple';
var estr = 'function ' + on + '() {} ' + on + '.prototype.getInfo = function() { return this.name; }; ';
eval.apply(global, [estr]);
// make a simple object from JSON:
// called many times
var apl = JSON.parse('{ "name": "Jason" }');
// force its class to be Foo
apl.__proto__ = global[on].prototype;
// this method works
console.log(apl.getInfo());
Maybe this?
var constructors = {
"Obj1": ObjConstructor1(){},
"Obj2": ObjConstructor2(){},
}
var obj = new constructors.Obj1();
var jsonObj = {"a":1,"b":2};
for (var x in jsonObj) {
obj[x] = jsonObj[x];
}