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!