PowerShell中如何将JSON对象C2合并到C1的resources数组中
合并JSON对象:将C2插入C1的resources数组
现有对象结构
C1结构
{ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "connections_TestValue_name": { "defaultValue": "TestValue", "type": "String" } }, "variables": {}, "resources": [] }
C2结构
{ "kind": "V2", "properties": { "displayName": "XXXX.XXX", "authenticatedUser": { "name": "XXX.XXX" }, "overallStatus": "Connected", "statuses": [ { "status": "Connected" } ], "connectionState": "Enabled", "parameterValues": {}, "customParameterValues": {} // 省略其他属性 } }
目标结构
{ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "connections_TestValue_name": { "defaultValue": "TestValue", "type": "String" } }, "variables": {}, "resources": [ { "kind": "V2", "properties": { // 保留C2的所有属性 } } ] }
实现方法
以下是几种常见脚本语言的实现方式(假设C1、C2已通过脚本获取为对应语言的对象/字典/自定义对象):
JavaScript/Node.js
// 将C2添加到C1的resources数组 C1.resources.push(C2); // 转为格式化后的JSON字符串输出 const mergedJson = JSON.stringify(C1, null, 2); console.log(mergedJson);
PowerShell
# 将C2添加到C1的resources数组 $C1.resources += $C2 # 转为格式化后的JSON字符串输出(-Depth需根据实际嵌套层级调整) $mergedJson = $C1 | ConvertTo-Json -Depth 10 Write-Output $mergedJson
Python
import json # 将C2添加到C1的resources数组 C1['resources'].append(C2) # 转为格式化后的JSON字符串输出 merged_json = json.dumps(C1, indent=2) print(merged_json)
内容的提问来源于stack exchange,提问作者Joy
相关产品推荐
相关产品推荐

