跳至內容

字典、雜湊映射和關聯陣列

字典(也稱為映射、雜湊映射或關聯陣列)是一組鍵/值對。OpenAPI 可讓您定義鍵為字串的字典。若要定義字典,請使用 type: object 並使用 additionalProperties 關鍵字來指定鍵/值對中值的類型。例如,如下所示的字串對字串字典

1
{ "en": "English", "fr": "French" }

是使用以下綱要定義的

1
type: object
2
additionalProperties:
3
type: string

值類型

additionalProperties 關鍵字指定字典中值的類型。值可以是基本類型(字串、數字或布林值)、陣列或物件。例如,字串對物件字典可以定義如下

1
type: object
2
additionalProperties:
3
type: object
4
properties:
5
code:
6
type: integer
7
text:
8
type: string

除了使用內嵌綱要之外,additionalProperties 也可以 $ref 另一個綱要

1
components:
2
schemas:
3
Messages: # <---- dictionary
4
type: object
5
additionalProperties:
6
$ref: "#/components/schemas/Message"
7
8
Message:
9
type: object
10
properties:
11
code:
12
type: integer
13
text:
14
type: string

自由格式物件

如果字典值可以是任何類型(亦稱自由格式物件),請使用 additionalProperties: true

1
type: object
2
additionalProperties: true

這相當於

1
type: object
2
additionalProperties: {}

固定金鑰

如果字典有一些固定金鑰,您可以將它們明確定義為物件屬性,並將它們標示為必要

1
type: object
2
properties:
3
default:
4
type: string
5
required:
6
- default
7
additionalProperties:
8
type: string

字典內容的範例

您可以使用 example 關鍵字來指定範例字典內容

1
type: object
2
additionalProperties:
3
type: string
4
example:
5
en: Hello!
6
fr: Bonjour!

沒有找到您要找的內容嗎?詢問社群
發現錯誤?請告訴我們