我们如何创建 JSON 模式以在普通 JSON 的基础上构建 angular 形式化的表单?
How can we create JSON schema to build a angular formly based forms on basis of plain JSON?
我们有一个要求,我们计划根据收到的 JSON 构建一个表单并将其转换为 formlyJsonschema 支持的 JSON 模式,有什么方法可以实现这个?
Eg JSON:
{
"isSignInRequired": true,
"isEmployee": false,
"noOfEmployees": {
"minValue": 3,
"maxValue": 50
}
}
要求:如果值为布尔值,则转换为切换类型,如果有整数或字符串值,则转换为文本框类型
想要转换的JSON formlyJsonschema支持的schema如下:
"schema" :[
{
"properties": {
"isSignInRequired": {
"type": "toggle",
"default": true
},
"isEmployee": {
"type": "toggle",
"default": true
}
}
},
{
"description": "noOfEmployees",
"type": "object",
"properties": {
"minValue": {
"type": "integer",
"title": "minValue"
},
"maxValue": {
"type": "integer",
"title": "maxValue",
"minLength": 3
}
}
}]
我尝试使用一些 JSON 基于模式的示例,但无法满足我的要求,示例如下:
default
和 maxLength
断言不可能从一个数据样本中得出,但您可以假设 type
和 properties
。您可能会选择假设其他断言,例如 additionalProperties
.
var data = {
"isSignInRequired": true,
"isEmployee": false,
"noOfEmployees": {
"minValue": 3,
"maxValue": 50
}
};
// could use lodash mapValues instead
var mapValues = (fn, data) => Object.keys(data).reduce((accum, key) => ({ ...accum, [key]: fn(data[key], key) }), {});
var toSchemaType = data =>
Array.isArray(data)
? 'array'
: typeof data;
var deriveSchema = (data, key) => ({
type: toSchemaType(data),
...(key && { title: key }),
...(toSchemaType(data) === 'object' && {
properties: mapValues(deriveSchema, data)
})
});
deriveSchema(data)
我们有一个要求,我们计划根据收到的 JSON 构建一个表单并将其转换为 formlyJsonschema 支持的 JSON 模式,有什么方法可以实现这个?
Eg JSON:
{
"isSignInRequired": true,
"isEmployee": false,
"noOfEmployees": {
"minValue": 3,
"maxValue": 50
}
}
要求:如果值为布尔值,则转换为切换类型,如果有整数或字符串值,则转换为文本框类型
想要转换的JSON formlyJsonschema支持的schema如下:
"schema" :[
{
"properties": {
"isSignInRequired": {
"type": "toggle",
"default": true
},
"isEmployee": {
"type": "toggle",
"default": true
}
}
},
{
"description": "noOfEmployees",
"type": "object",
"properties": {
"minValue": {
"type": "integer",
"title": "minValue"
},
"maxValue": {
"type": "integer",
"title": "maxValue",
"minLength": 3
}
}
}]
我尝试使用一些 JSON 基于模式的示例,但无法满足我的要求,示例如下:
default
和 maxLength
断言不可能从一个数据样本中得出,但您可以假设 type
和 properties
。您可能会选择假设其他断言,例如 additionalProperties
.
var data = {
"isSignInRequired": true,
"isEmployee": false,
"noOfEmployees": {
"minValue": 3,
"maxValue": 50
}
};
// could use lodash mapValues instead
var mapValues = (fn, data) => Object.keys(data).reduce((accum, key) => ({ ...accum, [key]: fn(data[key], key) }), {});
var toSchemaType = data =>
Array.isArray(data)
? 'array'
: typeof data;
var deriveSchema = (data, key) => ({
type: toSchemaType(data),
...(key && { title: key }),
...(toSchemaType(data) === 'object' && {
properties: mapValues(deriveSchema, data)
})
});
deriveSchema(data)