如何在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
}
}
}
2条答案
按热度按时间8wigbo561#
您可以使用
jsonschema
库在Python中生成JSON模式并根据模式进行验证。pip install jsonschema
先安装jsonschema
现在,您可以使用
jsonschema
为JSON结构生成JSON模式并验证它。例如:
您可以根据自己的具体要求自定义JSON模式。
jogvjijk2#
您可以使用
marshmallow
库指定要验证JSON的模式:让我们定义你的例子,看看我们如何根据这个模式来验证它们: