You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何定义键可任意(可选带限制)的键值对/哈希表/关联数组结构?

如何定义键可任意(带可选限制)的API对象

在API定义场景中,我们常处理固定键(部分可选)的对象,例如:

{
    "countryCode": "ITA",
    "countryName": "Italy"
}

但如果需要定义**键可任意(可选择性添加格式/规则限制)**的对象(比如以国家代码作为键),像下面这种结构:

{
    "ITA": "Italy",
    "FRA": "France"
}

可以根据你使用的技术规范(如TypeScript、JSON Schema、OpenAPI)采用以下方式实现:

1. TypeScript 中定义

使用索引签名来声明任意键的对象,还能通过类型约束限制键的格式:

  • 基础任意键定义:
// 所有键为字符串类型,值为字符串类型
type CountryMap = {
  [key: string]: string;
};
  • 带键格式限制的定义(比如仅允许三位大写字母作为键):
// 先定义符合规则的键类型
type CountryCode = `${Uppercase<string>}${Uppercase<string>}${Uppercase<string>}`;
// 基于该类型创建索引签名
type RestrictedCountryMap = {
  [key in CountryCode]: string;
};

2. JSON Schema 中定义

JSON Schema是API契约的常用规范,通过additionalProperties或patternProperties实现:

  • 允许任意字符串键,值为字符串:
{
  "type": "object",
  "additionalProperties": {
    "type": "string"
  }
}
  • 限制键必须是三位大写字母(同时禁止不符合规则的键):
{
  "type": "object",
  "patternProperties": {
    "^[A-Z]{3}$": {
      "type": "string"
    }
  },
  "additionalProperties": false
}

3. OpenAPI(Swagger)中定义

OpenAPI基于JSON Schema,写法类似:

components:
  schemas:
    CountryMap:
      type: object
      additionalProperties:
        type: string
    RestrictedCountryMap:
      type: object
      patternProperties:
        '^[A-Z]{3}$':
          type: string
      additionalProperties: false

内容的提问来源于stack exchange,提问作者rob74

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 07:01:06