前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用 Python 的 jsonsche

使用 Python 的 jsonsche

作者头像
py3study
发布2020-01-08 11:32:28
1.1K0
发布2020-01-08 11:32:28
举报
文章被收录于专栏:python3python3

在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)

代码语言:javascript
复制
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做了校验

代码语言:javascript
复制
    @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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档