How do I add one or more value to JSON using PowerShell?

How do I add value to the following JSON under Resource

{
“Sid”: “AmazonS3Access”,
“Effect”: “Allow”,
“Principal”: “",
“Action”: "s3:
”,
“Resource”: [
“arn:aws:s3:::123”,
“arn:aws:s3:::123/",
"arn:aws:s3:::456
”,
“arn:aws:s3:::456/*”
]
}

My target is to add following two value

“arn:aws:s3:::789*”
“arn:aws:s3:::789/*”

I have tried Add after importing JSON using ConvertFrom-Json, but didn’t work.

$ImpJSON.Resource.Add("“arn:aws:s3:::789*”")

 

Any idea?

Here is a solution to update your JSON object(s). Using ConvertFrom-Json will convert the JSON into usable PowerShell objects where you can then modify the members and values. Afterwards, convert the objects back to JSON and output back to the source file.

Though concatenating string arrays is inefficient, especially for larger collections, this is part of the solution:

# Source the JSON content
$jsonFilePath = 'file.json'
$jsonContent  = Get-Content -Path $jsonFilePath

Convert JSON to PSObjects

$jsonAsPsObjects = $jsonContent | ConvertFrom-Json

Collection for adding new items

$newResources = @(“arn:aws:s3:::789*”, “arn:aws:s3:::789/*”)

Add each item to Resource property

$newResources | ForEach-Object -Process { $jsonAsPsObjects.Resource += $_ }

Save JSON back to file

$jsonAsPsObjects | ConvertTo-Json | Out-File -Path $jsonFilePath