You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中生成指定JSON的JSON Schema并验证JSON合法性

在Python中生成JSON Schema并验证JSON实例

一、生成符合要求的JSON Schema

根据你提出的三个要求,对应的JSON Schema定义如下:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "required": ["type", "properties"],
    "properties": {
        "type": {
            "type": "string",
            "enum": ["csv", "json", "CSV", "JSON"]
        },
        "properties": {
            "type": "object",
            "minProperties": 1,
            "patternProperties": {
                "^.*$": {
                    "type": "object",
                    "required": ["type", "index"],
                    "properties": {
                        "type": {
                            "type": "string",
                            "enum": ["string", "number"]
                        },
                        "index": {
                            "type": "integer",
                            "minimum": 0
                        }
                    },
                    "additionalProperties": false
                }
            },
            "additionalProperties": false,
            "allOf": [
                {
                    "contains": {
                        "properties": {
                            "index": {"const": 0},
                            "type": {"const": "string"}
                        },
                        "required": ["index", "type"]
                    }
                }
            ]
        }
    },
    "additionalProperties": false
}

Schema对应要求的说明

  • 要求1:通过type字段的enum限定取值只能是csv/json(包含大小写形式),同时顶层required确保该字段必须存在;
  • 要求2:properties字段被定义为对象类型,patternProperties匹配任意列名,每个列的属性必须包含type和index,且不允许额外属性;
  • 要求3:通过allOf结合contains规则,确保至少存在一列的index为0且type为string。

二、Python中验证JSON实例

使用jsonschema库可以快速完成验证,步骤如下:

1. 安装依赖库

pip install jsonschema

2. 验证代码实现

from jsonschema import validate, ValidationError

# 定义上述JSON Schema
schema = {
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "required": ["type", "properties"],
    "properties": {
        "type": {
            "type": "string",
            "enum": ["csv", "json", "CSV", "JSON"]
        },
        "properties": {
            "type": "object",
            "minProperties": 1,
            "patternProperties": {
                "^.*$": {
                    "type": "object",
                    "required": ["type", "index"],
                    "properties": {
                        "type": {
                            "type": "string",
                            "enum": ["string", "number"]
                        },
                        "index": {
                            "type": "integer",
                            "minimum": 0
                        }
                    },
                    "additionalProperties": false
                }
            },
            "additionalProperties": false,
            "allOf": [
                {
                    "contains": {
                        "properties": {
                            "index": {"const": 0},
                            "type": {"const": "string"}
                        },
                        "required": ["index", "type"]
                    }
                }
            ]
        }
    },
    "additionalProperties": false
}

# 验证函数
def check_json_validity(instance):
    try:
        validate(instance=instance, schema=schema)
        print("✅ JSON实例符合Schema要求")
    except ValidationError as e:
        print(f"❌ JSON实例不符合Schema要求:{e.message}")

# 测试有效示例
valid_example = {
    "type": "csv",
    "properties": {
        "header1": {
            "type": "string",
            "index": 0
        },
        "header2": {
            "type": "number",
            "index": 1
        }
    }
}

# 测试无效示例
invalid_example = {
    "type": "CSV",
    "properties": {
        "header1": {
            "type": "bool"
        },
        "header2": {
            "type": "number",
            "index": 1
        }
    }
}

# 执行验证
check_json_validity(valid_example)
check_json_validity(invalid_example)

3. 运行结果

  • 有效示例输出:✅ JSON实例符合Schema要求
  • 无效示例输出:❌ JSON实例不符合Schema要求: 'index' is a required property(同时隐含type字段取值不符合枚举的问题,jsonschema会按顺序抛出错误)

内容的提问来源于stack exchange,提问作者Harish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 12:07:07