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

Detect if a json schema has a oneOf type schema

我想检查一个模式是否只有一个模式,或者它是否有多个模式,其中一个 属性。

python代码应该是这样的

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

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

架构 1

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

架构 2

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

如何在 Python 中执行此操作?

编辑:更正了我的示例架构

这里是一个示例,显示了一种递归检查提供的 json 中是否有一个 属性 的方法。如果您特别想只检查 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"

带输出的调用示例[​​=12=]

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