简体   繁体   中英

How to add objects to a blank array in a json file using powershell

here is my json body .

{
    "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": ""
        }
    }
}

I want to add some values inside the brackets at "triggers": [], What I'm trying to get is:

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

i tried -replace and replace() saving the json file to local system, but none of them are working, I even tried to edit the json file directly like this but failed.

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

Please help.

You can import the json file as PowerShell objects, manipulate the structure until it looks the way you want it to and export it back to json format:

$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

As it was pointed out in the comments, it is of course also possible to import the trigger definition from a json file instead of building it in a hash table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM