JSONSchema形式数据和普通数组对象结构数据相互转化
convertFromJSONSchema(jsonSchema) {
const processProperties = (properties, required = []) =>
Object.entries(properties).map(([key, prop]) => {
const item = {
paramsName: key,
paramsDesc: prop.description || '',
paramsType: prop.type,
paramsRequired: required.includes(key)
};
if (prop.type === 'object' && prop.properties) {
item.children = processProperties(prop.properties, prop.required || []);
} else if (prop.type === 'array' && prop.items && prop.items.properties) {
item.children = processProperties(prop.items.properties, prop.items.required || []);
}
return item;
});
return jsonSchema && jsonSchema.properties
? processProperties(jsonSchema.properties, jsonSchema.required || [])
: [];
},
convertToJSONSchema(data) {
const convertParamsToSchema = ({ paramsType, paramsDesc, paramsRequired, children, paramsName }) => {
const paramSchema = {
type: paramsType,
description: paramsDesc,
...(paramsRequired && { required: true })
};
if (paramsType === "object" || paramsType === "array") {
const properties = {};
const required = [];
children.forEach(child => {
properties[child.paramsName] = convertParamsToSchema(child);
if (child.paramsRequired) {
required.push(child.paramsName);
}
});
if (paramsType === "object") {
paramSchema.properties = properties;
if (required.length) {
paramSchema.required = required;
}
} else {
paramSchema.items = { type: "object", properties };
if (required.length) {
paramSchema.items.required = required;
}
}
}
return paramSchema;
};
return data.map(item => ({
type: "object",
properties: {
[item.paramsName]: convertParamsToSchema(item)
},
...(item.paramsRequired && { required: [item.paramsName] })
}));
},