生成JSON模式并根据模式验证JSON

wvt8vs2t  于 2023-05-19  发布在  其他
关注(0)|答案(2)|浏览(147)

如何在Python中为下面的JSON生成JSON模式,并根据模式验证每个JSON?
要求:

  • 有一种类型可以是CSV或JSON或JSON
  • 有一个属性列表。
  • 每个属性都有一个键,它是一个列名,值是一个定义列属性的字典。第一列col1具有属性类型字符串,并且对应于索引零。
{
            "type": "csv/json",
            "properties": {
                "col1": {
                    "type": "string",
                    "index":0
                },
                "col2": {
                    "type": "number",
                    "index":1
                },....
            }
        }

如何为这个json生成一个JSON模式?
有效json示例

{
    "type": "csv",
    "properties": {
        "header1": {
            "type": "string",
            "index":0
        },
        "header2": {
            "type": "number",
            "index":1
        }   
    }
}

示例无效的JSON(因为header 1的类型是bool,并且缺少index属性)

{
    "type": "CSV",
    "properties": {
        "header1": {
            "type": "bool"
        },
        "header2": {
            "type": "number",
            "index":1
        }   
    }
}
8wigbo56

8wigbo561#

您可以使用jsonschema库在Python中生成JSON模式并根据模式进行验证。
pip install jsonschema先安装jsonschema
现在,您可以使用jsonschema为JSON结构生成JSON模式并验证它。
例如:

import jsonschema
from jsonschema import validate

# Define the JSOn schema
schema = {
    "type": "object",
    "properties": {
        "type": {"enum": ["csv", "json"]},
        "properties": {
            "type": "object",
            "patternProperties": {
                "^.*$": {
                    "type": "object",
                    "properties": {
                        "type": {"type": "string"},
                        "index": {"type": "integer"},
                    },
                    "required": ["type", "index"],
                }
            },
            "additionalProperties": False,
        },
    },
    "required": ["type", "properties"],
}

# Sample valid JSON
valid_json = {
    # Your Sample valid JSON Goes here..
    },
}

# Sample invalid JSON
invalid_json = {
    # Your Invalidate JSON Goes here..
    },
}

# Validate JSON against the schema
try:
    validate(instance=valid_json, schema=schema)
    print("Valid JSON")
except jsonschema.exceptions.ValidationError as e:
    print("Invalid JSON:", e)

try:
    validate(instance=invalid_json, schema=schema)
    print("Valid JSON")
except jsonschema.exceptions.ValidationError as e:
    print("Invalid JSON:", e)

您可以根据自己的具体要求自定义JSON模式。

jogvjijk

jogvjijk2#

您可以使用marshmallow库指定要验证JSON的模式:

from marshmallow import Schema, fields, validate

class ColumnProperty(Schema):
    type = fields.Str(
        required=True,
        validate=validate.OneOf(["string", "number"])
    )
    index = fields.Integer(
        required=True
    )

class JSONSchema(Schema):
    type = fields.Str(
        required=True,
        validate=validate.OneOf(["json", "csv", "csv/json"])
    )
    properties = fields.Dict(
        keys=fields.String(),
        values=fields.Nested(ColumnProperty)
    )

让我们定义你的例子,看看我们如何根据这个模式来验证它们:

# instantiate schema
schema = JSONSchema()

example_data1 = {
    "type": "csv/json",
    "properties": {
        "col1": {
            "type": "string",
            "index":0
            },
        "col2": {
            "type": "number",
            "index":1
            }
    }
}

result = schema.load(example_data1)  # passes

example_data2 = {
    "type": "csv",
    "properties": {
        "header1": {
            "type": "string",
            "index":0
        },
        "header2": {
            "type": "number",
            "index":1
        }   
    }
}

result = schema.load(example_data2)  # passes

example_data3 = {
    "type": "CSV",
    "properties": {
        "header1": {
            "type": "bool"
        },
        "header2": {
            "type": "number",
            "index":1
        }   
    }
}

result = schema.load(example_data3) # raises: ValidationError: {'properties': defaultdict(<class 'dict'>,
 # {'header1': {'value': {'index': ['Missing data for required field.'], 
 # 'type': ['Must be one of: string, number.']}}}), 'type': ['Must be one of: json, csv, csv/json.']}

相关问题