【问题标题】:How to add objects to a blank array in a json file using powershell如何使用powershell将对象添加到json文件中的空白数组
【发布时间】:2021-09-28 12:41:59
【问题描述】:

这是我的 json 正文。

{
    "source": 2,
    "revision": 3,
    "description": null,    
    "triggers": [],
    "releaseNameFormat": "Release-$(rev:r)",
    "tags": [],
    "pipelineProcess": {
        "type": 1
    },
    "properties": {
        "DefinitionCreationSource": {
            "$type": "System.String",
            "$value": "BuildSummary"
        },
        "System.EnvironmentRankLogicVersion": {
            "$type": "System.String",
            "$value": "2"
        }
    },
    "id": 5,
    "name": "CheckListAPI - CD",
    "path": "\\Admin",
    "projectReference": null,
    "url": "",
    "_links": {
        "self": {
            "href": ""
        },
        "web": {
            "href": ""
        }
    }
}

我想在“触发器”的括号内添加一些值:[], 我想要得到的是:

"triggers": 
    [
    {
            "artifactAlias": "_DV_NJ_PIPE",
            "triggerConditions": [],
            "triggerType": 1
    }
    ],

我试过 -replace 和 replace() 将 json 文件保存到本地系统,但它们都不起作用,我什至尝试像这样直接编辑 json 文件但失败了。

$alias = $json.triggers
foreach ($artifact in $alias )
{
$artifact.artifactAlias = "_$DefName"
$artifact.triggerConditions = "{}"
$artifact.triggertype = "artifactSource"
}

请帮忙。

【问题讨论】:

    标签: arrays json powershell


    【解决方案1】:

    您可以将 json 文件作为 PowerShell 对象导入,操作结构直到它看起来像您想要的那样,然后将其导出回 json 格式:

    $pipeline = Get-Content .\input.json | ConvertFrom-Json
    
    $trigger = [ordered]@{
        artifactAlias = "_DV_NJ_PIPE"
        triggerConditions = @()
        triggerType = 1
    }
    $pipeline.triggers += $trigger
    
    $pipeline | ConvertTo-Json -Depth 5 | Out-File .\output.json
    

    正如在 cmets 中所指出的,当然也可以从 json 文件中导入触发器定义,而不是在哈希表中构建它。

    【讨论】:

    • 由于 $trigger 在问题中也以Json 字符串的形式给出,您可以参考它(而不是从有序字典中重建它):$Trigger = ConvertFrom-Json '{"artifactAlias":"_DV_NJ_PIPE","triggerConditions":[],"triggerType":1}'
    • @iRon 谢谢,我打错了赋值运算符。它现在固定了。关于从 json 导入触发器定义与在哈希表中构建它:在这种情况下,后者对我来说似乎更明智。
    猜你喜欢
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2020-04-26
    • 2011-11-21
    相关资源
    最近更新 更多