Powershell: How to Update/Replace data and values in Json and XML Object

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

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…


Then if we want to update Oranges from 2 to 100 we simply change the value:

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.

Lastly, since candies is defined as an array in the JSON we can simply add the desired candy to the array.

Source:

Powershell: How to Update/Replace data and values in Json and XML Object by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply