Find and Replace all instances of a value in JSON with different value in Powershell

592 views Asked by At

I have large JSON with a value that needs to be replaced with some other value. Basically I am trying to do find and replace all in powershell. I would like to remove where ever we see Rock to Rocky

JSON

{
  "Customer": [
    {
      "id": "123"
    }
  ],
  "Nationality": [
    {
      "name": "US",
      "id": "456"
    }
  ],
  "address": [
    {
      "$type": "Home",
      "name": "Houston",
      "streets": [
        {
          "name": "Union",
          "postalCode": "10",
        }
      ]
    },
    {
      "$type": "Office",
      "name": "Hawai",
      "streets": [
        {
          "name": "Rock",
          "postalCode": "11",
        }
      ]
    },
    {
      "$type": "Office1",
      "name": "Hawaii",
      "streets": [
        {
          "name": "Rock 678",
          "postalCode": "11",
        }
      ]
    },
    {
      "$type": "Office2",
      "name": "Hawai2",
      "streets": [
        {
          "name": "Rock",
          "postalCode": "11",
        }
      ]
    }
    
  ]
}

I am changing the JSON to object but not sure how can I find and replace all. I would like to remove where ever we see Rock to Rocky

Code

$FileContent = Get-Content -Path "Test.json" -Raw | ConvertFrom-Json
$FileContent.address.streets.name = 'Rocky' // I want to do for all the instances.

$FileContent | ConvertTo-Json -Depth 100 | Out-File "Test.json" -Force
1

There are 1 answers

0
חִידָה On BEST ANSWER

How to Replace string value in File using Powershell?

  • Replacing 'Rock' with 'Rocky' ;

  • Set-Content in the file.

    (Get-Content -path C:\Users\Username\Folder\File.json -Raw) -replace 'Rock' , 'Rocky' | Set-Content -path C:\Users\Username\Folder\File.json;