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

如何从JSON数组中根据operation_name获取对应的operation_id值

匹配指定operation_name并获取对应operation_id的实现方法

首先修正你给出的JSON为标准格式(键和字符串需加双引号):

[
  {
    "operation_id": 2,
    "operation_name": "FAITHFUL BELIEVERS"
  },
  {
    "operation_id": 3,
    "operation_name": "SAMPLE OP"
  },
  {
    "operation_id": 4,
    "operation_name": "SAMPLE OP 2"
  }
]

下面是两种常用编程语言的实现方式:

JavaScript 实现

用数组的find()方法直接定位目标对象,再提取operation_id:

// 解析后的JS对象数组(如果原始是JSON字符串,先用JSON.parse()转换)
const operations = [
  {operation_id: 2, operation_name: "FAITHFUL BELIEVERS"},
  {operation_id: 3, operation_name: "SAMPLE OP"},
  {operation_id: 4, operation_name: "SAMPLE OP 2"}
];

// 查找operation_name为'SAMPLE OP'的对象
const targetOp = operations.find(op => op.operation_name === 'SAMPLE OP');

// 输出结果,找不到时给出提示
if (targetOp) {
  console.log(targetOp.operation_id); // 控制台输出3
} else {
  console.log("没找到匹配的operation_name");
}

Python 实现

可以用循环遍历或者生成器表达式快速筛选:

循环遍历方式

operations = [
    {"operation_id": 2, "operation_name": "FAITHFUL BELIEVERS"},
    {"operation_id": 3, "operation_name": "SAMPLE OP"},
    {"operation_id": 4, "operation_name": "SAMPLE OP 2"}
]

target_id = None
for op in operations:
    if op["operation_name"] == "SAMPLE OP":
        target_id = op["operation_id"]
        break

# 打印结果
print(target_id if target_id else "未找到匹配项") # 输出3

简洁的生成器方式

operations = [
    {"operation_id": 2, "operation_name": "FAITHFUL BELIEVERS"},
    {"operation_id": 3, "operation_name": "SAMPLE OP"},
    {"operation_id": 4, "operation_name": "SAMPLE OP 2"}
]

# 找到就返回对应id,找不到返回None
target_id = next((op["operation_id"] for op in operations if op["operation_name"] == "SAMPLE OP"), None)
print(target_id if target_id else "未找到匹配项")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 15:15:45