Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically generate JavaScript from JSON Schema

After hourlong searching I have found no solution about my problem and now I hope someome could be able to help me here.

So basically what I am looking for is a way to generate a JavaScript file (*.js) from a JSON (Schema) file automatically using NodeJS. I know that there are things like fs.write, but this is surely no fitting way for my problem, I think. And so far I have found no other way to create my JavaScript file other than that.

Basically I want to translate:

{
"type":"object",
"properties": {
    "name": {
        "type": "string"
    },
    "age": {
        "type": "integer",
        "default":12
    },
    "favorite_color": {
        "type": "string"
    },
    "gender": {
        "type": "string",
        "enum": [
            "male",
            "female"
        ]
    }
}
}

Into JavaScript code like:

var data = function() { 

    data.baseConstructor.call(this);
    this.name = ko.observable("");
    this.age = ko.obseravble(12);
    this.favorite_color = ko.observable();
    this.gender = ko.observable(data.genderModes.male);

}

data.genderModes = {

   male: "male",
   female: "female" 
}

Would someone be able to give me a hint to my problem?

like image 440
Stefan C. Avatar asked Oct 31 '22 09:10

Stefan C.


1 Answers

I don't know how to convert your json to js function but if you want to create object from json schema, you could use json-schema-defaults. After creating one object with json-schema-defaults you can create anothers with Object.create and you can add first level properties to new objects which is created by Object.create function.

var a = require('json-schema-defaults')({
"type":"object",
"properties": {
    "name": {
        "type": "string"
    },
    "age": {
        "type": "integer",
        "default":12
    },
  }
});

var b = Object.create(a,{
                         id:{ value:1 }, 
                          f:{ value:function() { 
                                     console.log('run lola run');
                                    }
                            }
                         }
                       );
like image 174
uzay95 Avatar answered Nov 09 '22 05:11

uzay95