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

基于@ports字段对ports数组进行删除元素的JSON转换需求

解决方案

方案1:使用JQ工具(推荐的轻量JSON处理方案)

JQ是专门用于JSON处理的命令行工具,能快速实现这类数组过滤需求。

核心命令

jq '.[].\"n-services\".\"n-service\" |= map(.ports = [range(0; length) as $i | select(."@ports"[$i]?.["my:operation"] != "delete") | .ports[$i]])' input.json

命令说明

  • 定位目标数组:.[].\"n-services\".\"n-service\"精准找到需要处理的n-service数组
  • 遍历处理每个服务项:|= map(...)对数组内的每个服务对象执行修改逻辑
  • 构建新的ports数组:
    • range(0; length) as $i遍历ports数组的所有索引
    • select(."@ports"[$i]?.["my:operation"] != "delete")跳过@ports中标记为delete的索引项(?.避免null值报错)
    • .ports[$i]保留未被标记删除的端口值

执行命令后,输出的ports数组会自动移除@ports中标记delete对应位置的元素,得到你需要的[3500, 3505]。

方案2:Python脚本自定义处理

如果需要更灵活的逻辑扩展,可编写Python自定义脚本:

脚本代码

import json

# 读取输入JSON文件
with open('input.json', 'r', encoding='utf-8') as f:
    json_data = json.load(f)

# 遍历每个服务项处理ports数组
for service_item in json_data[0]['n-services']['n-service']:
    original_ports = service_item['ports']
    port_ops = service_item['@ports']
    filtered_ports = []
    
    for idx, op in enumerate(port_ops):
        # 跳过标记为delete的端口,保留其他端口
        if not op or op.get('my:operation') != 'delete':
            filtered_ports.append(original_ports[idx])
    
    # 更新ports字段
    service_item['ports'] = filtered_ports

# 写入输出JSON文件
with open('output.json', 'w', encoding='utf-8') as f:
    json.dump(json_data, f, indent=2)

脚本说明

  • 加载JSON数据后,遍历每个n-service对象
  • 配对@ports的操作和ports的端口值,过滤掉操作为delete的对应端口
  • 将处理后的数组重新赋值给ports字段,最后保存为新的JSON文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 22:17:48