簡介
JSON 作為通用的前后端交互,或者后台服務間通信的通用格式被大家廣泛使用。我們肯定遇到過一些場景需要校驗調用方傳遞過來的數據格式,比如一定要包含某些字段,某個字段一定要符合某種格式,比如定義了價格的字段,范圍一定要在100~200之間,協議字段一定要是TCP或者UDP等枚舉類型。你是否在你的用戶代碼里面自行實現這些判斷邏輯呢?如果這樣的規則越來越多是不是會顯得代碼很臃腫呢?這就是為什么要介紹我們今天的主角JSON Schema。JSON Schema定義了JSON格式的規范,各種語言都有開源的第三方JSON Schema校驗庫,例如Go語言的gojsonschema,這樣我們就可以定義一份JSON Schema,然后系統的各個模塊都可以復用這套JSON規范,不滿足規則的數據JSON Schema會直接報錯。
語法說明
JSON Schema作為JSON的規范樣式,自身也有一套key-value語法用於聲明各種規則。
key | value | 備注 |
$schema | http://json-schema.org/draft-04/schema# http://json-schema.org/draft-06/schema# http://json-schema.org/draft-07/schema# |
說明是哪個版本的JSON Schema,不同版本間不完全兼容 |
type | string、number、integer、boolean、object等 例如{"type":"integer"}說明該字段一定要是整形 |
說明字段的類型 |
pattern | { |
正則表達式 |
enum | { "type": "string", |
枚舉類型 |
properties | 說明該JSON對象有哪些屬性/字段 "properties": { |
屬性字段 |
definitions | 通常搭配$ref一起說明使用 { "$ref": "#/definitions/address" } |
自定義字段 |
$ref | 通常用於復雜說明 | 引用字段 |
required | "required": ["street_address", "city", "state"] | 必須字段 |
oneof | { // 10 yes // 9 yes // 2 no |
滿足其中一個 |
allof | { // "short" yes // "too long" no |
滿足全部 |
multipleOf | { "type": "number", "multipleOf": 5 }, | 倍數 |
not | { "not": { "type": "string" } } // 42 yes //"hello" no |
取反 |
array | { |
數組 |
propertyNames | 正則字符串 | 定義key的正則規則 |
patternProperties | { |
同時限定key和value |
additionalProperties | boolean | 是否允許有格外的屬性 |
dependencies | { // { "gender":"male" } no |
屬性間依賴關系 |
uniqueItems | boolean | 數組元素是否唯一 |
minProperties/maxProperties | number | 最小/大屬性個數 |
用法示例
定義JSON Schema規則:
{ "$schema": "https://json-schema.org/draft-04/schema#", "type": "object", "properties":{ "schema_version": { "type": "string" }, "service": { "$ref": "#/definitions/service" } }, "additionalProperties": false, "required": [ "schema_version", "service" ], "definitions": { "service": { "type": "object", "properties": { "name": { "$ref": "#/definitions/service_name" }, "runtime": { "$ref": "#/definitions/runtime_location" }, "labels": { "$ref": "#/definitions/service_labels" }, "selector": { "$ref": "#/definitions/service_selector" }, "ports": { "$ref": "#/definitions/service_ports" } }, "required": [ "name", "runtime", "labels", "selector", "ports" ] }, "service_name": { "type": "string", "pattern": "^[a-z0-9-]+.[a-z0-9-]+$" }, "service_labels": { "type": "object", "properties": { "group": { "type": "string" }, "balance_strategy": { "enum": [ "source", "roundrobin", "leastconn" ]} } }, "service_ports": { "type": "array", "uniqueItems": true, "minItems": 1, "items": { "type": "object", "additionalProperties": false, "properties": { "name": { "type": "string" }, "domain_name": { "type": "string" }, "path": { "type": "string" }, "port": { "type": "integer", "minimum": 0, "exclusiveMinimum": true }, "protocol": { "enum": [ "tcp", "udp", "http" ] } }, "required": [ "name", "protocol", "port" ] } }, "label_value": { "type": "string", "pattern": "(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])" }, "version": { "type": "string", "pattern": ",^\\d+(\\.\\d+)+" }, "service_selector": { "type": "object", "propertyNames": { "pattern": "[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*" }, "patternProperties": { "[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*": { "$ref":"#/definitions/label_value" } } }, "runtime_location": { "type": "string", "pattern": "^[a-zA-Z0-9-_]+\\.[a-zA-Z0-9-_]+\\.[a-z0-9-_]+$" } } }
保存為schema.json文件,后面代碼會用到。
需要校驗的JSON數據為:
{ "schema_version":"0.1.0", "service":{ "name":"template-service", "runtime":"30007.xx7.abc", "labels":{ "group":"external", "balance_strategy":"roundrobin" }, "selector":{ "podname":"haha4-tester" }, "ports":[ { "name":"http8088", "domain_name":"yyy.xxx.com", "path":"/test/", "port":8088, "protocol":"http" }, { "name":"tcp-00", "port":8800, "protocol":"tcp" } ] } }
保存為document.json文件。
代碼示例
下面我將用golang的第三方開源庫gojsonschema校驗上面的JSON數據是否符合我們定義的JSON Schema。
package main import ( "fmt" "github.com/xeipuuv/gojsonschema" "io/ioutil" ) func main() { schemaContent, err := ioutil.ReadFile("schema.json") if err != nil { panic(err.Error()) } jsonContent, err := ioutil.ReadFile("document.json") if err != nil { panic(err.Error()) } loader1 := gojsonschema.NewStringLoader(string(schemaContent)) schema, err := gojsonschema.NewSchema(loader1) if err != nil { panic(err.Error()) } documentLoader := gojsonschema.NewStringLoader(string(jsonContent)) result, err := schema.Validate(documentLoader) if err != nil { panic(err.Error()) } if result.Valid() { fmt.Printf("The document is valid\n") } else { fmt.Printf("The document is not valid. see errors :\n") for _, desc := range result.Errors() { fmt.Printf("- %s\n", desc) } } }
程序運行輸出:
The document is valid
總結
通過上面的介紹和代碼示例,我們可以清楚的了解到了JSON Schema定義JSON數據規范的便利性和通用性,我們可以將JSON Schema應用到我們的代碼用,減少JSON數據的校驗冗余代碼。
參考
https://json-schema.org/understanding-json-schema/reference/index.html
https://json-schema.org/learn/getting-started-step-by-step.html
https://github.com/xeipuuv/gojsonschema