检测json模式是否具有oneOf类型模式

时间:2017-12-11 21:40:50

标签: python json jsonschema json-schema-validator

我想检查架构中是否只有一个架构,或者它是否有一个带有oneOf属性的架构。

python代码应该是这样的

If schema1 has oneOf property:
    Some code1
If schema1 is just a single schema:
    Some code2

基本上我希望能够区分这两种类型的模式

Schema1

"schema1": {
    "definitions": {
        "schema": {
            "type": "object",
            "properties": {
                "name": {
                    "type": ["string", "null"]
                }
            }
        }
    }
}

SCHEMA2

"schema2": {
    "definitions": {
        "schema": {
            "oneOf": [
            {
                "type": ["null"]
            },
            {
                "type": ["string"],
                "enum": ["NONE"]
            }
            ]
        }
    }
}

我怎样才能在Python中执行此操作?

修改:更正了我的示例架构

1 个答案:

答案 0 :(得分:1)

这是一个示例,显示了一种递归检查所提供的json中是否存在oneOf属性的方法。如果您特别想要检查json的'schema'部分,则需要检查父属性。

#!/usr/bin/env python

import json


def objectHasKey(object_,key_):
    _result = False 
    if (type(object_)==dict):
        for _key in object_.keys():
            print _key
            if (type(object_[_key])==dict):
                _dict = object_[_key]
                _result = objectHasKey(_dict,key_)
            if _key == key_:
                _result = True
            if _result:
                break
    return _result

firstJSONText = '''
{
    "definitions": {
        "schema": {
            "type": "object",
            "properties": {
                "name": {
                    "type": [
                        "string",
                        "null"
                    ]
                }
            }
        }
    }
}
'''

first = json.loads(firstJSONText)

secondJSONText = '''
{
    "definitions": {
        "schema": {
            "oneOf": [
                {
                    "type": [
                        "null"
                    ]
                },
                {
                    "type": [
                        "string"
                    ],
                    "enum": [
                        "NONE"
                    ]
                }
            ]
        }
    }
}
'''

second = json.loads(secondJSONText)

target = first

if objectHasKey(target,'oneOf'):
    print "Handle oneOf with first"
else:
    print "Handle default with first"

target = second

if objectHasKey(target,'oneOf'):
    print "Handle oneOf with second"
else:
    print "Handle default with second"

带输出的示例调用

csmu-macbook-pro-2:detect-if-a-json-schema-has-a-oneof-type-schema admin$ ./test-for-schema.py 
definitions
schema
type
properties
name
type
Handle default with first
definitions
schema
oneOf
Handle oneOf with second