是否有任何库可以从 JSON 模式生成 Javascript 类型的对象(JS 函数)?基本上相当于这个 http://code.google.com/p/jsonschema2pojo/ 的 JS 版本. 谢谢。
编辑:
开始于:
{
"description": "An entity",
"type":"object",
"properties": {
"geometries": {"type": "array",
"items": {
"$ref" : "geometry"
}
}
}
}
我希望为我生成这样的代码
function Entity {
this.geometries;
}
显然,使用 $ref 等的模式可能会更复杂,我希望这能给出想法。
最佳答案
这是djvi吗?库是否满足您的要求?
提供的示例显示:
var jsonSchema = {"common":{"properties":{"type":{"enum":["common"]}},"required":["type"]}};
var env = new djvi();
env.addSchema('test', jsonSchema);
env.instance('test#/common');
// => { type: 'common' }
我怀疑这就是您所追求的解决方案。
现在这不是您想要的确切解决方案,但我遇到了类似的问题并创建了以下解决方案以将父对象作为函数返回,它可能会有所帮助:
var dbdict = {
"title": "Entity",
"description": "An entity",
"type":"object",
"properties": {
"geometries": {"type": "array",
"items": {
"$ref" : "geometry"
}
}
}
}
var walkJSONSchema = function (JSONSchema, returnFunction) {
var walkObject = function(PROPS) {
var $this = this,
$child = {}
;
if(returnFunction == true) {
$child = new function() {};
}
//console.log("PROPS");
//console.log(PROPS);
for(var key in PROPS) {
console.log("key:"+key+" type:"+PROPS[key].type+" default:"+PROPS[key].default);
switch(PROPS[key].type) {
case "boolean":
$child[key] = PROPS[key].default || undefined;
break;
case "integer":
case "number":
$child[key] = PROPS[key].default || undefined;
break;
case "array":
$child[key] = [].push($this.walkObject(PROPS[key].properties));
break;
case "object":
$child[key] = $this.walkObject(PROPS[key].properties);
break;
case "string":
$child[key] = PROPS[key].default || undefined;
break;
};
};
return $child;
}
return walkObject(JSONSchema.properties);
}
Entity = walkJSONSchema(dbdict, true);
当然,您可以按照自己喜欢的方式编写从模式文档中检索“实体”的脚本,但这样至少您可以获得一个函数。
关于javascript - JSON 模式到 Javascript 类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13028400/