JSON Schema指的是數據交換中的一種虛擬的“合同”。
JSON驗證器負責驗證語法錯誤,JSON Schema負責提供一致性檢驗。
JSON Schema是數據接收方額第一道防線,也是數據發送方節約時間、保證數據正確的好工具。
JSON Schema可以解決下列有關一致性驗證的問題。
1、 值的數據類型是否正確:可以具體規定一個值是數字、字符串等類型;
2、 是否包含所需的數據:可以規定哪些數據是需要的,哪些是不需要的;
3、 值的形式是不是我需要的:可以指定範圍、最小值和最大值。
編寫JSON Schema的步驟:
一、在JSON第一個名稱——值對中,聲明其爲一個schema文件。聲明的名稱必須爲”$schema”,值必須爲所用草擬版本的連接:
{
"$schema": "http://json-schema.org/draft-04/schema#",
}
二、第二個名稱——值對是JSON Schema文件格式,比如表示一隻貓:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title":"cat"
}
三、定義title的相關屬性值:
"properties":{
"name":{
"type":"string"
},
"age":{
"type":"number",
"description":"Your cat's age in years"
},
"declawed":{
"type":"boolean"
},
"description":{
"type":"string"
}
}
四、完整的Json Schema代碼如下:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title":"cat",
"properties":{
"name":{
"type":"string"
},
"age":{
"type":"number",
"description":"Your cat's age in years"
},
"declawed":{
"type":"boolean"
},
"description":{
"type":"string"
}
},
"required":[
"name",
"age",
"declawed"
]
}
完整的案例:
1、驗證貓的完整JSON代碼
{
"name":"TOM",
"age":2,
"declawed":false,
"description":"TOM loves to sleep all day."
}
其中required定義的是必填字段。
在線測試網址:
http://www.jsonschemavalidator.net/
本文參考JSON必知必會編寫。