How to Edit a JSON File in PowerShell (With Example)


Often you may want to edit the values in a JSON file using PowerShell.

Here is an example of how to do so:

$file = Get-Content my_teams.json -raw | ConvertFrom-Json
$file | % {if($_.Location -eq 'Dallas'){$_.Name='Mavs'}}
$file | ConvertTo-Json -depth 32 > new_teams.json

Here is what this particular example does:

  • First, retrieve the JSON file named my_teams.json
  • Next, for each value in the Location field of the file that is equal to ‘Dallas’, update the corresponding value in the Name field to be equal to ‘Mavs’
  • Lastly, output these changes to a new JSON file named new_teams.json

Note: The default value for depth when using ConvertTo-Json is 2, but we specify a depth of 32 in this example to avoid any issues that may arise from not having a deeply enough nested JSON.

The following example shows how to use this syntax in practice.

Example: How to Edit a JSON File in PowerShell

Suppose that we have a JSON file named my_teams.json with information about various basketball teams.

We can use the following syntax to view the contents of this file:

Get-Content my_teams.json

The following screenshot shows how to use this syntax in practice:

Suppose that we would like to find all values in the Location field of the file that are equal to ‘Dallas’ and change the corresponding value in the Name field to be ‘Mavs’ instead.

We can use the following syntax to do so:

$file = Get-Content my_teams.json -raw | ConvertFrom-Json
$file | % {if($_.Location -eq 'Dallas'){$_.Name='Mavs'}}
$file | ConvertTo-Json -depth 32 > new_teams.json

The following screenshot shows how to use this syntax in practice:

PowerShell edit JSON file

Notice that when we use the Get-Content cmdlet to view the contents of the new file named new_teams.json we can see that ‘Mavericks’ has been renamed to ‘Mavs’ in the first Name field of the file.

Note: You can find the complete documentation for the ConvertTo-Json cmdlet in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Sort a Table with Format-Table
PowerShell: How to Sort by Specific Column
PowerShell: How to Use Sort-Object with Multiple Properties

Leave a Reply