我正在努力用PowerShell将一些JSON代码添加到现有文件中.

下面是必须添加到文件中特定位置的json块.

$manualInterventionJson = @"
{
    "deploymentInput": {
        "parallelExecution": {
            "parallelExecutionType": 0
        },
        "timeoutInMinutes": 0,
        "jobCancelTimeoutInMinutes": 1,
        "condition": "succeeded()",
        "overrideInputs": {}
    },
    "rank": 2,
    "phaseType": 2,
    "name": "Agentless job",
    "refName": null,
    "workflowTasks": [
        {
            "environment": {},
            "taskId": "bcb64569-d51a-4af0-9c01-ea5d05b3b622",
            "version": "8.*",
            "name": "Manual Intervention",
            "refName": "",
            "enabled": true,
            "alwaysRun": false,
            "continueOnError": false,
            "timeoutInMinutes": 0,
            "retryCountOnTaskFailure": 0,
            "definitionType": "task",
            "overrideInputs": {},
            "condition": "succeeded()",
            "inputs": {
                "instructions": "test blablabla",
                "emailRecipients": "",
                "onTimeout": "reject"
            }
        }
    ]
}
"@

Json文件具有复杂的 struct .以下是一个示例版本:

{
    "source": 2,
    "variables": {},
    "environments": [{
        "name": "Deploy",
        "rank": 1,
        "deployPhases": [{            
            "rank": 1,
            "phaseType": 1,
            "name": "Agent job",
            "refName": null,
            "workflowTasks": [{
                "environment": {},
                "taskId": "##TASK_GROUP_ID##",
                "version": "1.*",
                "name": "##TASK_GROUP_NAME##",
                "condition": "succeededOrFailed()",
                "inputs": {}
            }]
        }],
        "postDeploymentGates": {
            "id": 0,
            "gatesOptions": null
        },
        "environmentTriggers": []
    }]
}

请注意,目前只有1个部署阶段(级别1),必须添加级别2,即顶部的json块.

This may also help in replicating the issue: enter image description here

这就是最终的结果:

enter image description here

我用.Add()来测试数组,用+=Add-Member来测试,我甚至try 创建一个新的字典对象$obj = New-Object "System.Collections.Generic.Dictionary[[String],[String]]",但这也不起作用,因为有些值是不同类型的.

编辑:PS.我不需要保存更新后的文件.只需读取文件$jsonObj = Get-Content "C:\temp\test.json" -Raw | ConvertFrom-Json,更新变量中的内容,无需保存到文件中.

在这一点上,我可以得到一些指导.谢谢.

推荐答案

deployPhases属性包含一个数组,因此创建字典在这里没有帮助.

我会将数组子表达式运算符@(...)Sort-Object结合使用:

# parse both the original document and the document to be inserted
$original = Get-Content "C:\temp\test.json" -Raw | ConvertFrom-Json
$newPhase = $manualInterventionJson |ConvertFrom-Json

# get a reference to the parent object
$targetEnvironment = $original.environments |Select -First 1

# construct a new deployPhases array by concatenating the new document and sorting by rank
$newDeployPhases = @(
  @($targetEnvironment.deployPhases;$newPhase) |Sort-Object rank
)

# overwrite existing deployPhases property with new list
$targetEnvironment.deployPhases = $newDeployPhases

# and finally convert the modified object hierarchy back to json
$modifiedJson = $original |ConvertTo-Json -Depth 15

$modifiedJson现在包含所需的更新

Json相关问答推荐

从json数组中删除特定元素

Vega图表计数聚合如果数据值为空数组则不显示任何内容,如何解决此问题?

PowerShell脚本未按预期生成预期的JSON输出

过go 24小时内判断员事件的EventBridge事件模式

使用 Powershell,如何将 Azure AD 组成员转换为 Json 对象(文件),然后可以更新?

删除 JOLT 中的方括号

取消嵌套数组并将数组名称添加为附加字段

Powershell v7 文本背景突出显示

用于遮蔽卡的 Jolt 规格

如何在循环中传递列表(会话(字符串属性))以在 Gatling Scala 中创建批量 Json 请求

如何使用 CORS 实现 JavaScript Google Places API 请求

如何使用 Newtonsoft.Json 反序列化 JSON 数组

Android 上的 JSON - 序列化

在 JSON 反序列化期间没有为System.String类型定义无参数构造函数

如何通过 NSJSONSerialization 在 JSON 中包含空值?

如何在 django rest 框架中定义列表字段?

将文件发送到 Rails JSON API

Jsonpath 与 Jackson 或 Gson

有没有办法使用 Jackson 将 Map 转换为 JSON 表示而不写入文件?

字符串格式 JSON 字符串给出 KeyError