Home > front end >  Json text replace in string array using PowerShell
Json text replace in string array using PowerShell

Time:02-18

Objective: to change from "some" to "that" in string array in Json

Json:

{
  "resources": [
    {
      "name": "item1",
      "dependsOn": [
        "somevalue",
        "somevalue"
      ]
    },
    {
      "name": "item2",
      "dependsOn": [
        "somemorevalue",
        "someothervalue"
      ]
    },
    {
      "name": "item3",
      "dependsOn": [
        "somemorevalue",
        "someothervalue"
      ]
    }
  ]
}

PowerShell Code:

$t = Get-Content -path "data.json" -Raw | ConvertFrom-Json

$t.resources | ForEach-Object {
    $_ = $_.dependsOn | ForEach-Object {
        $_ = $_ -replace "some", "that"
    }
}

$t.resources 

OutPut: I am getting following output after running the code. Could you help me what I am missing here?

name  dependsOn
----  ---------
item1 {somevalue, somevalue}
item2 {somemorevalue, someothervalue}
item3 {somemorevalue, someothervalue}

CodePudding user response:

You never assign anything back to the dependsOn property, hence the lack of persistence.

Change the second statement to:

$t.resources | ForEach-Object {
    $_.dependsOn = @($_.dependsOn -replace "some", "that")
}

Note that -replace can be applied to multiple input strings, so the inner ForEach-Object statement is unnecessary.

CodePudding user response:

You can replace values in place within foreach-loop in Powershell, but for that you need to modify fields of $_ instead of directly assigning a value to $_. Therefore in order to replace your dependsOn stuff, you need to recreate a part or the entire object $t by first returning the changed strings, then assigning the returned array or object to exact part of a bigger structure. Like this:

$t.resources | ForEach-Object {
    $_.dependsOn = $_.dependsOn | ForEach-Object {
        $_ -replace "some", "that"
    }
}

$t.resources 

Here, first you call a foreach loop on a nested object's dependsOn array, but instead of assigning the value, you return it as an item not passed to any assignment, this instead goes outside the loop forming the array output of the foreach block. Then you assign the altered output to the processed object's field, instead of modifying the temporary variable $_ you dereference it thus gaining access to the exact object being processed, and are able to replace the value for dependsOn array with altered data.

  • Related