Typescript+React项目中jsonforms适配的JSON结构转换实现
入参到jsonforms格式的转换实现方案
前置类型补全
解决TypeScript动态键赋值的类型拦截问题,定义好输入输出对应的类型结构:
// 已定义的输入结构 interface inputProps { name: string; type: string; allowed_values?: string[]; } export interface ProjectInput { inputProperties: inputProps[]; } // 补充输出端类型,避免动态键赋值时报错 type SchemaPropertyEntry = { type: string; enum?: string[]; } type SchemaPropertiesDict = Record<string, SchemaPropertyEntry>
核心转换逻辑
使用Array.prototype.reduce构建目标字典结构,逻辑闭环,不容易出现作用域污染、对象初始化遗漏的问题:
/** * 将解析后的输入属性数组转换为jsonforms兼容的properties结构 * @param propertyList 类型为inputProps[]的入参数组 * @returns 符合要求的properties字典 */ const buildSchemaProperties = (propertyList: inputProps[]): SchemaPropertiesDict => { return propertyList.reduce((dict, currentItem) => { // 以条目name值作为对象键,基础值为类型字段 dict[currentItem.name] = { type: currentItem.type } // 当allowed_values存在非空内容时,追加enum字段 if (currentItem.allowed_values && currentItem.allowed_values.length > 0) { dict[currentItem.name].enum = currentItem.allowed_values } return dict }, {} as SchemaPropertiesDict) }
高频踩坑说明
- 对象初始化位置错误:需要将properties空对象定义在循环逻辑外侧,不能在循环内部每次生成新对象,否则最终返回的结构会是空值。
- 字段映射错位:原始入参的数组字段为
availableProperties时,需要从解析后的JSON根对象上直接取该字段,不要错按接口里定义的inputProperties取值,否则会拿到undefined值导致遍历不执行。 - 类型校验拦截:未定义
Record结构的输出类型时,TypeScript会默认将空对象识别为固定结构,给自定义动态键赋值时会抛出类型错误,阻断编译流程。
实际调用示例
解析外部传入的JSON文件后,直接调用转换函数即可得到目标结构:
// 解析后的原始JSON结构 const externalInput = { "availableProperties": [ { "name":"color", "type": "string", "allowed_values": [] }, { "name":"size", "type": "string", "allowed_values": ["small","medium","large"] }, { "name":"amount", "type": "number", "allowed_values": [] } ] } // 生成可直接传给jsonforms组件的完整schema const jsonFormsSchema = { type: 'object', properties: buildSchemaProperties(externalInput.availableProperties as inputProps[]) }
内容的提问来源于stack exchange,提问作者Thorsten Steparsch
相关产品推荐
相关产品推荐

