json schema校驗


工作中使用到了json schema格式校驗的問題,在網上查了些資料,結合自己的理解記錄一下。

json schema可以對json結果字符串做出一些約束,例如:

1. 值類型是:array, object, number, string等等

2.值類型必須是枚舉中的一個

3. 字符串的長度限制

4. 對字符串判斷是否符合正則表達式

5. array元素個數

6. object對象必要屬性

 

測試schema文件

 1 {
 2     "$schema": "http://json-schema.org/draft-04/schema#",
 3     "title": "Product set",
 4     "type": "array",  5     "items": {
 6         "title": "Product",
 7         "type": "object",  8         "properties": {
 9             "name": {
10                 "type": "string"
11             },
12             "price": {
13                 "type": "number",
14                 "minimum": 0,
15                 "maximum":30,
16                 "exclusiveMinimum": true
17             },
18             "tags": {
19                 "type": "array",
20                 "items": {
21                     "type": "string",
22                     "minLength":10,
23                     "maxLength":1024,
24                     "pattern":"http://.*"
25                 },
26                 "minItems": 2, 27                 "uniqueItems": true
28             },
29             "city":{
30               "type":"string",
31               "enum" : ["bj", "sh", "hk"] 32             }
33         },
34         "required": ["name", "price"] 35     }
36 }

 

測試json

 1 [
 2   {
 3     "name":"san",
 4     "price":29,
 5     "tags":["http://sdtr/sdg", "http://qwewret/qsdf"],
 6     "city":"bj"
 7   },
 8   {
 9     "name":"dong",
10     "price":30,
11     "tags":["http://test", "http://sina"],
12     "city":"hk"
13   },
14 ]

 

參考:

http://blog.csdn.net/Miss_Ashelley/article/details/53285762

http://www.jsonschemavalidator.net/

http://json-schema.org/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM