0

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}

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it worked, I was trying the same with $_ =$_ -replace in the inner loop, but it wasn't working. Thanks Again.
@SanjeevKumar $_ = $_ -replace ... only overwrites the contents of the $_ variable - it doesn't modify the object that was previously stored in it
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.