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

如何使用json_modify.py修改Azure网卡JSON中的键名?

修改Azure网卡JSON中ip_configurations数组的键名

要实现将azure_network_interface_info下ip_configurations数组内的public_ip_address键重命名为public_ip_address_name,你需要通过读取原键值→添加新键赋值→删除旧键这三步操作完成,因为json_modify的update仅负责修改值,无法直接重命名键。以下是具体实现方案:

假设你的原始JSON结构

{
  "azure_network_interface_info": {
    "ip_configurations": [
      {
        "name": "ipconfig-01",
        "public_ip_address": "pip-web-01",
        "private_ip_address": "172.16.0.5"
      },
      {
        "name": "ipconfig-02",
        "public_ip_address": "pip-db-01",
        "private_ip_address": "172.16.0.6"
      }
    ]
  }
}

具体代码实现

import json
from json_modify import JsonModify

# 加载目标JSON文件(也可以直接传入内存中的JSON数据)
with open("azure_nic_data.json", "r", encoding="utf-8") as f:
    nic_data = json.load(f)

# 初始化JsonModify实例
jm = JsonModify(nic_data)

# 遍历ip_configurations数组的每个元素,逐个修改键名
for idx in range(len(jm["azure_network_interface_info"]["ip_configurations"])):
    # 构造当前元素的路径
    elem_path = f"azure_network_interface_info.ip_configurations[{idx}]"
    # 1. 获取原键的值
    pip_value = jm[f"{elem_path}.public_ip_address"].get()
    # 2. 添加新键并赋值
    jm[f"{elem_path}.public_ip_address_name"].update(pip_value)
    # 3. 删除旧键
    jm[elem_path].delete("public_ip_address")

# 保存修改后的JSON
with open("modified_azure_nic_data.json", "w", encoding="utf-8") as f:
    json.dump(jm.data, f, indent=2, ensure_ascii=False)

优化说明(避免键不存在的报错)

如果部分ip_configurations元素可能没有public_ip_address键,可以添加存在性判断:

for idx in range(len(jm["azure_network_interface_info"]["ip_configurations"])):
    elem_path = f"azure_network_interface_info.ip_configurations[{idx}]"
    if jm[elem_path].has("public_ip_address"):
        pip_value = jm[f"{elem_path}.public_ip_address"].get()
        jm[f"{elem_path}.public_ip_address_name"].update(pip_value)
        jm[elem_path].delete("public_ip_address")

简化写法(若json_modify支持数组遍历)

如果你的json_modify版本支持数组的each遍历方法,可简化为:

jm["azure_network_interface_info"]["ip_configurations"].each(
    lambda elem: elem.update({"public_ip_address_name": elem.get("public_ip_address")})
                    .delete("public_ip_address")
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 22:27:32