JSONSchema形式数据和普通数组对象结构数据相互转化

2023-12-26 19:36:15

JSONSchema形式数据和普通数组对象结构数据相互转化

// 将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 || [])
        : [];
},



// 将数据处理成JSONSchema形式
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] })
    }));
},      

文章来源:https://blog.csdn.net/xiaomao_wxj/article/details/135229088
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。