使用 Python 的 jsonschema 对 json 做验证

来源:互联网 发布:淘宝达人5篇帖子 编辑:程序博客网 时间:2024/05/16 12:10

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

[html] view plain copy
  1. list_agents = {  
  2.     'status_code': [200],  
  3.     'response_body': {  
  4.         'type': 'object',  
  5.         'properties': {  
  6.             'agents': {  
  7.                 'type': 'array',  
  8.                 'items': {  
  9.                     'type': 'object',  
  10.                     'properties': {  
  11.                         'agent_id': {'type': 'integer'},  
  12.                         'hypervisor': {'type': 'string'},  
  13.                         'os': {'type': 'string'},  
  14.                         'architecture': {'type': 'string'},  
  15.                         'version': {'type': 'string'},  
  16.                         'url': {'type': 'string', 'format': 'uri'},  
  17.                         'md5hash': {'type': 'string'}  
  18.                     },  
  19.                     'required': ['agent_id', 'hypervisor', 'os',  
  20.                                  'architecture', 'version', 'url', 'md5hash']  
  21.                 }  
  22.             }  
  23.         },  
  24.         'required': ['agents']  
  25.     }  
  26. }  


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

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

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

[python] view plain copy
  1. @classmethod  
  2. def validate_response(cls, schema, resp, body):  
  3.     # Only check the response if the status code is a success code  
  4.     # TODO(cyeoh): Eventually we should be able to verify that a failure  
  5.     # code if it exists is something that we expect. This is explicitly  
  6.     # declared in the V3 API and so we should be able to export this in  
  7.     # the response schema. For now we'll ignore it.  
  8.     if resp.status in HTTP_SUCCESS:  
  9.         cls.expected_success(schema['status_code'], resp.status)  
  10.   
  11.         # Check the body of a response  
  12.         body_schema = schema.get('response_body')  
  13.         if body_schema:  
  14.             try:  
  15.                 jsonschema.validate(body, body_schema)  
  16.             except jsonschema.ValidationError as ex:  
  17.                 msg = ("HTTP response body is invalid (%s)") % ex  
  18.                 raise exceptions.InvalidHTTPResponseBody(msg)  
  19.         else:  
  20.             if body:  
  21.                 msg = ("HTTP response body should not exist (%s)") % body  
  22.                 raise exceptions.InvalidHTTPResponseBody(msg)  
  23.   
  24.         # Check the header of a response  
  25.         header_schema = schema.get('response_header')  
  26.         if header_schema:  
  27.             try:  
  28.                 jsonschema.validate(resp, header_schema)  
  29.             except jsonschema.ValidationError as ex:  
  30.                 msg = ("HTTP response header is invalid (%s)") % ex  
  31.                 raise exceptions.InvalidHTTPResponseHeader(msg)  


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

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

0 0
原创粉丝点击