Update JSON file without destroying JSON format

Question:

I’m trying to update a Swagger JSON document in Powershell. I need to add a couple of properties and values if they do not already exist on the object.

The code for doing this is pretty simple:

The problem I have is that the JSON gets completely destroyed when I save it back to the file: For example

becomes

I haven’t seen any other examples on how to do this in Powershell, is there some syntax or parameter I am missing in order to retain the original format?

Answer:

When using ConvertTo-Json, use -Depth to retain proper format of the JSON.

For Example:

I also had to add brackets around your JSON to make it valid JSON readable by powershell.

Source:

Update JSON file without destroying JSON format by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply