工作中使用到了json schema格式校验的问题,在网上查了些资料,结合自己的理解记录一下。
json schema可以对json结果字符串做出一些约束,例如:
1. 值类型是:array, object, number, string等等
2.值类型必须是枚举中的一个
3. 字符串的长度限制
4. 对字符串判断是否符合正则表达式
5. array元素个数
6. object对象必要属性
测试schema文件
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Product set",
"type": "array",
"items": {
"title": "Product",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"price": {
"type": "number",
"minimum": 0,
"maximum":30,
"exclusiveMinimum": true
},
"tags": {
"type": "array",
"items": {
"type": "string",
"minLength":10,
"maxLength":1024,
"pattern":"http://.*"
},
"minItems": 2,
"uniqueItems": true
},
"city":{
"type":"string",
"enum" : ["bj", "sh", "hk"]
}
},
"required": ["name", "price"]
}
}
测试json
[
{
"name":"san",
"price":29,
"tags":["http://sdtr/sdg", "http://qwewret/qsdf"],
"city":"bj"
},
{
"name":"dong",
"price":30,
"tags":["http://test", "http://sina"],
"city":"hk"
},
]
参考:
http://blog.csdn.net/Miss_Ashelley/article/details/53285762
http://www.jsonschemavalidator.net/
http://json-schema.org/