使用 Python 的 jsonschema 对 json 做验证

在OpenStack中, 使用了Python的 jsonschema包, 对json字符串做了验证.


Python JSON Schema Library

https://pypi.python.org/pypi/jsonschema


JSON Schema Introduction

http://json-schema.org/


做法比较简单

1) 定义一个文件 json schema. json schema 类似于一个模板定义文件, 定义了json中的节点名称, 节点值类型

以tempest中的一个schema定义为例 (tempest/api_schema/compute/agents.py)

list_agents = {
    'status_code': [200],
    'response_body': {
        'type': 'object',
        'properties': {
            'agents': {
                'type': 'array',
                'items': {
                    'type': 'object',
                    'properties': {
                        'agent_id': {'type': 'integer'},
                        'hypervisor': {'type': 'string'},
                        'os': {'type': 'string'},
                        'architecture': {'type': 'string'},
                        'version': {'type': 'string'},
                        'url': {'type': 'string', 'format': 'uri'},
                        'md5hash': {'type': 'string'}
                    },
                    'required': ['agent_id', 'hypervisor', 'os',
                                 'architecture', 'version', 'url', 'md5hash']
                }
            }
        },
        'required': ['agents']
    }
}


2) 使用jsonschema包, 对json字符串和json schema做对比, 进行验证

以下代码来自于 /tempest/common/rest_client.py. 

tempest对每一个REST api的返回值, 都使用json schema做了校验

    @classmethod
    def validate_response(cls, schema, resp, body):
        # Only check the response if the status code is a success code
        # TODO(cyeoh): Eventually we should be able to verify that a failure
        # code if it exists is something that we expect. This is explicitly
        # declared in the V3 API and so we should be able to export this in
        # the response schema. For now we'll ignore it.
        if resp.status in HTTP_SUCCESS:
            cls.expected_success(schema['status_code'], resp.status)

            # Check the body of a response
            body_schema = schema.get('response_body')
            if body_schema:
                try:
                    jsonschema.validate(body, body_schema)
                except jsonschema.ValidationError as ex:
                    msg = ("HTTP response body is invalid (%s)") % ex
                    raise exceptions.InvalidHTTPResponseBody(msg)
            else:
                if body:
                    msg = ("HTTP response body should not exist (%s)") % body
                    raise exceptions.InvalidHTTPResponseBody(msg)

            # Check the header of a response
            header_schema = schema.get('response_header')
            if header_schema:
                try:
                    jsonschema.validate(resp, header_schema)
                except jsonschema.ValidationError as ex:
                    msg = ("HTTP response header is invalid (%s)") % ex
                    raise exceptions.InvalidHTTPResponseHeader(msg)


Java 中, 也有一个json-schema-validator的实现, 用法可以参考

http://stackoverflow.com/questions/14511468/java-android-validate-string-json-against-string-schema



你可能感兴趣的:(Tempest,Python)