Question:
So I am having a bit of a problem here, I can’t seem to figure out how to update data values in an Object
so lets say for example the FOLLOWING json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
{ "People": 263, "Hungry": true, "Fruits": { "Apples": 1 "Oranges": 2 }, "Places": { "Places": [{ "Baskets": "true", "name": "Room 1", "candycount": 1500, "candytypespresent": { "candies": [ "caramel" ] } }, { "Baskets": "false", "name": "Room 2", "candycount": 2000, "candytypespresent": { "candies": [ "caramel", "jawbreaker", "butterscotch" ] } } ] } } |
I have Powershell read it smoothly with convertfrom-json
How would I do the following:
A) Change “Oranges” from “2” to “100”
B) “Baskets” in Room 2 from “false” to “true”
C) add “bubblegum” to “candies” in Room1
HOW can I update this without rewriting the WHOLE json or object?
Answer:
The JSON becomes a custom object with nested objects, so really it is fairly simple. To start, let’s fix the JSON by adding a comma after the Apples value, and convert it to an object…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
$JSON = @' { "People": 263, "Hungry": true, "Fruits": { "Apples": 1, "Oranges": 2 }, "Places": { "Places": [ { "Baskets": "true", "name": "Room 1", "candycount": 1500, "candytypespresent": { "candies": [ "caramel" ] } }, { "Baskets": "false", "name": "Room 2", "candycount": 2000, "candytypespresent": { "candies": [ "caramel", "jawbreaker", "butterscotch" ] } } ] } } '@ | ConvertFrom-JSON |
Then if we want to update Oranges from 2 to 100 we simply change the value:
1 2 |
$JSON.Fruits.Oranges = 100 |
Similarly we can modify the Room 2 by simply listing the Places, passing it to a
Where
statement to get the right room, and modify the value in a ForEach
loop.
1 2 |
$JSON.Places.Places | Where{$_.name -eq 'Room 2'} | ForEach{$_.Baskets = 'true'} |
Lastly, since
candies
is defined as an array in the JSON we can simply add the desired candy to the array.
1 2 |
$JSON.Places.Places | Where{$_.name -eq 'Room 1'} | ForEach{$_.CandyTypesPresent.candies += 'bubblegum'} |