ConvertTo Json - PowerShell


Overview

ConvertTo-Json converts an object to a JSON (JavaScript Object Notation) string representation. It is useful for sending objects to other systems or for storing data in a text-based format.

Syntax

ConvertTo-Json [-InputObject] <Object>
             [-Compress]
             [-Depth <Int32>]
             [-ErrorAction <ActionPreference>]
             [-GroupBy <String(1)>]
             [-Namespace <String>]
             [-OutVariable <String>]
             [-TypeNameHandling <TypeNameHandling>]

Options/Flags

  • -InputObject: Specifies the object to convert to JSON.
  • -Compress: Compresses the output JSON string.
  • -Depth: Sets the maximum depth of the converted JSON object.
  • -ErrorAction: Specifies the action to take when an error occurs.
  • -GroupBy: Groups the properties of the converted object by the specified property name.
  • -Namespace: Specifies the namespace to use for properties.
  • -OutVariable: Stores the output JSON string in the specified variable.
  • -TypeNameHandling: Specifies how to handle type information in the JSON string.

Examples

Simple JSON Conversion

$obj = Get-Process
$json = $obj | ConvertTo-Json

Compressing JSON Output

$json = Get-Process | ConvertTo-Json -Compress

Limiting Object Depth

$json = Get-Process | ConvertTo-Json -Depth 2

Grouping Properties

$json = Get-Process | ConvertTo-Json -GroupBy Name

Common Issues

Excessive Output Size: The uncompressed JSON output can be large for complex objects. Use the -Compress option to reduce the size.

Type Loss: By default, type information is lost during conversion. Use the -TypeNameHandling option to retain type information.

Integration

ConvertTo-Json often serves as an intermediate step in data exchange or storage. It can be used with other commands for automated tasks, such as:

  • Exporting data to a JSON file: ConvertTo-Json | Out-File -FilePath "data.json"
  • Sending JSON data to a web service: ConvertTo-Json | Invoke-RestMethod -Uri "https://example.com/api"
  • ConvertFrom-Json: Converts a JSON string to an object.
  • Export-Clixml: Exports an object to a CLIXML (Command Line Interface XML) file.
  • Format-List: Formats an object as a list of properties.