PowerShell: How to Save JSON Object to a File


Often you may want to use PowerShell to save a JSON object to a file.

You can use the following syntax to do so:

$my_data | ConvertTo-Json -Depth 32 | Set-Content my_json_data.txt

This particular example saves the JSON object named $my_data to a  file named my_json_data.txt.

Note that we first use the ConvertTo-Json cmdlet to convert the object to a JSON formatted object. 

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.

We then use the Set-Content cmdlet to save the contents of the JSON object to a text file in the current directory.

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

Example: How to Save JSON Object to a File in PowerShell

Suppose that we first create the following hash table in PowerShell named $my_data that contains information about a particular basketball player:

$my_data = @{
  'League' = @{
    'Player' = @{
      'Team' = 'Lakers'
      'Points' = '35'
      'Rebounds' = '11'
    }
  }
}

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

Suppose that we would like to convert this object to a JSON formatted object and then save it to a text file.

We can use the following syntax to do so:

$my_data | ConvertTo-Json -Depth 32 | Set-Content my_json_data.txt

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

PowerShell save JSON to file

Notice that when we use the Get-Content cmdlet to view the contents of the new file named my_json_data.txt we can see that the JSON formatted object has been successfully saved to 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 Edit a JSON File
PowerShell: Use ConvertTo-Json on Array with Single Item
PowerShell: How to Loop Through Each Line of CSV File

Leave a Reply