'Json text replace in string array using PowerShell
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}
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vesper |
