參考

數值型別

JSON Schema 中有兩種數值型別:integernumber。它們共用相同的驗證關鍵字

JSON 沒有表示複數的標準方法,因此在 JSON Schema 中無法測試它們。

integer

integer 型別用於整數。JSON 沒有明確的整數和浮點數型別。因此,小數點的存在與否不足以區分整數和非整數。例如,11.0 是在 JSON 中表示相同值的兩種方式。JSON Schema 認為無論使用哪種表示法,該值都是整數。

特定語言資訊:
Python
Ruby
Objective-C
Swift
在 Python 中,「integer」類似於 int 型別。
schema
{ "type": "integer" }
資料
42
符合 schema
資料
-1
符合 schema

小數部分為零的數字被視為整數

資料
1.0
符合 schema

浮點數會被拒絕

資料
3.1415926
不符合 schema

以字串表示的數字會被拒絕

資料
"42"
不符合 schema

number

number 型別用於任何數值型別,無論是整數還是浮點數。

特定語言資訊:
Python
Ruby
Objective-C
Swift
在 Python 中,「number」類似於 float 型別。
schema
{ "type": "number" }
資料
42
符合 schema
資料
-1
符合 schema

簡單的浮點數

資料
5.0
符合 schema

指數符號也適用

資料
2.99792458e8
符合 schema

以字串表示的數字會被拒絕

資料
"42"
不符合 schema

倍數

可以使用 multipleOf 關鍵字,將數字限制為給定數字的倍數。它可以設定為任何正數。

schema
{ "type": "number", "multipleOf" : 10}
資料
0
符合 schema
資料
10
符合 schema
資料
20
符合 schema
資料
23
不符合 schema

倍數可以是浮點數

schema
{ "type": "number", "multipleOf" : 0.01}
資料
4.02
符合 schema
資料
4.021
不符合 schema

範圍

數字的範圍是使用 minimummaximum 關鍵字組合指定(或是使用 exclusiveMinimumexclusiveMaximum 來表示排除範圍)。

如果 *x* 是正在驗證的值,則以下條件必須為真

xminimum
x > exclusiveMinimum
xmaximum
x < exclusiveMaximum

雖然您可以同時指定 minimumexclusiveMinimum,或是同時指定 maximumexclusiveMaximum,但這樣做其實沒有意義。

schema
{ "type": "number", "minimum": 0, "exclusiveMaximum": 100}

小於 minimum

資料
-1
不符合 schema

minimum 是包含性的,所以 0 是有效的

資料
0
符合 schema
資料
10
符合 schema
資料
99
符合 schema

exclusiveMaximum 是排除性的,所以 100 是無效的

資料
100
不符合 schema

大於 maximum

資料
101
不符合 schema
草案特定資訊:
草案 4

在 JSON Schema 草案 4 中,exclusiveMinimumexclusiveMaximum 的運作方式不同。它們在那裡是布林值,表示 minimummaximum 是否排除該值。例如

如果 exclusiveMinimumfalse,則 xminimum
如果 exclusiveMinimumtrue,則 x > minimum

此變更旨在使其更具關鍵字獨立性。

以下是使用較舊的 Draft 4 慣例的範例

schema
{ "type": "number", "minimum": 0, "maximum": 100, "exclusiveMaximum": true}

小於 minimumjson // props { "indent": true, "valid": false } -1 exclusiveMinimum 未指定,因此包含 0

資料
0
符合 schema
資料
10
符合 schema
資料
99
符合 schema

exclusiveMaximumtrue,因此不包含 100

資料
100
不符合 schema

大於 maximum

資料
101
不符合 schema

需要協助嗎?

您覺得這些文件有幫助嗎?

幫助我們使文件更完善!

在 JSON Schema,我們重視文件貢獻,如同其他類型的貢獻!

仍然需要協助嗎?

學習 JSON Schema 通常令人困惑,但別擔心,我們在這裡提供協助!