Welcome Forums General PowerShell Q&A How do I add one or more value to JSON using PowerShell?

Viewing 1 reply thread
  • Author
    Posts
    • #167530
      Participant
      Topics: 1
      Replies: 0
      Points: 7
      Rank: Member

      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?

    • #173305
      Participant
      Topics: 10
      Replies: 119
      Points: 533
      Helping Hand
      Rank: Major Contributor

      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
Viewing 1 reply thread
  • The topic ‘How do I add one or more value to JSON using PowerShell?’ is closed to new replies.