使用 Python 的 jsonschema 对 json 做验证
2016-10-29 17:50
246 查看
在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
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做了校验
[python] view
plain copy
@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
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
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做了校验
[python] view
plain copy
@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
相关文章推荐
- 使用 Python 的 jsonschema 对 json 做验证
- python+httplib实现HTTP POST提交数据,使用Basic Authentication(基本验证)做登陆验证
- python 使用SAX解析器验证xml文件格式是否完好
- python使用json格式进行数据封装
- iOS使用ASIHttpRequest+Json与服务器段脚本进行登陆验证
- Python中使用Json 以及 Python2.7中json库Bug的处理
- 使用Python多线程抓取并验证代理
- 使用python解析json文件
- python simplejson模块的使用方法
- Python代理抓取并验证使用多线程实现
- Python--使用json.dumps 将 json 格式的数据写到文件里--with open as f
- python——使用yaml数据格式,PK --> XML,JSON
- Android Json的使用(1) 使用jsonschema2pojo生成class文件
- 使用PYTHON登陆验证网站的几种方式!
- 使用python解析json文件
- 使用python验证想法
- python simplejson模块的使用方法
- python使用json格式进行数据封装
- python simplejson模块的使用方法
- Python JSON的使用