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

如何用Shell脚本通过嵌套循环将环境变量转为指定JSON格式

需求描述

我的abc.env文件包含以下条目:

connection_name_1=xyz
connection_name_2=gsh
schema_1_connection_name_1=dsd
schema_2_connection_name_1=rwf
schema_1_connection_name_2=dfs

需要按规则关联connection_name和对应的schema条目:

  • connection_name_1关联:schema_1_connection_name_1、schema_2_connection_name_1
  • connection_name_2关联:schema_1_connection_name_2

最终生成如下结构的JSON文件:

{
  "connection_specific_details": [
    {
      "connection_name": "xyz",
      "schemas": [
        {
          "dbUser": "dsd"
        },
        {
          "dbUser": "rwf"
        }
      ]
    },
    {
      "connection_name": "gsh",
      "schemas": [
        {
          "dbUser": "dfs"
        }
      ]
    }
  ]
}
实现方案(Python脚本)

用以下脚本即可完成.env文件解析与目标JSON生成:

import json
from collections import defaultdict

# 读取.env文件
env_path = 'abc.env'
conn_map = {}
schema_data = defaultdict(list)

with open(env_path, 'r') as f:
    for line in f:
        line = line.strip()
        if not line or '=' not in line:
            continue
        key, val = line.split('=', 1)
        # 记录连接名映射
        if key.startswith('connection_name_'):
            conn_map[key] = val
        # 关联schema到对应连接
        elif key.startswith('schema_'):
            conn_key = '_'.join(key.split('_')[2:])
            if conn_key in conn_map:
                schema_data[conn_key].append(val)

# 构建目标JSON结构
result = {"connection_specific_details": []}
for conn_key, conn_name in conn_map.items():
    result["connection_specific_details"].append({
        "connection_name": conn_name,
        "schemas": [{"dbUser": user} for user in schema_data.get(conn_key, [])]
    })

# 写入输出文件
with open('connection_details.json', 'w') as f:
    json.dump(result, f, indent=2)

脚本说明:

  1. 逐行读取.env文件,过滤无效行后拆分键值对
  2. 单独存储connection_name_*类型的条目,建立键与连接名的映射
  3. 对schema_*类型的条目,提取后缀的connection_name_*键,将对应的dbUser值关联到该连接
  4. 按要求的结构组装数据,最终写入JSON文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 15:02:03