ConvertFrom Json - PowerShell


Overview

ConvertFrom-Json parses a JSON string and converts it into a PowerShell object. It’s a versatile tool for transforming structured JSON data into a format compatible with PowerShell scripts and workflows.

Syntax

ConvertFrom-Json -InputObject <string> [-Depth <int>] [-AsHashTable] [-ErrorAction <ErrorAction>] [-WarningAction <WarningAction>] [-InformationAction <InformationAction>] [-Verbose] [-Debug] [-ErrorVariable <string>] [-WarningVariable <string>] [-InformationVariable <string>] [-OutVariable <string>]

Options/Flags

  • -Depth: Specifies the maximum depth of JSON object nesting to convert. Default: 2
  • -AsHashTable: Converts the JSON object to a PowerShell hashtable instead of a custom object.
  • -ErrorAction: Specifies the action to take on errors. Default: Stop
  • -WarningAction: Specifies the action to take on warnings. Default: Continue
  • -InformationAction: Specifies the action to take on information messages. Default: Continue
  • -Verbose: Enables verbose output for detailed execution information.
  • -Debug: Enables debug output for troubleshooting.
  • -ErrorVariable: Stores any errors in the specified variable.
  • -WarningVariable: Stores any warnings in the specified variable.
  • -InformationVariable: Stores any information messages in the specified variable.
  • -OutVariable: Stores the output object in the specified variable.

Examples

Simple Conversion:

$json = '{"name": "John Doe", "age": 30}'
$person = ConvertFrom-Json -InputObject $json

Conversion to HashTable:

$hashtable = ConvertFrom-Json -InputObject $json -AsHashTable

Limiting Conversion Depth:

$json = '{"name": "John Doe", "nested": {"address": "123 Main St"}}'
$person = ConvertFrom-Json -InputObject $json -Depth 1

Common Issues

  • Parse Errors: Ensure the JSON string is correctly formatted without syntax errors.
  • Nested Object Access: Use the . operator to access nested objects in the converted object.
  • Type Mismatch: If the converted object’s data types don’t match your expectations, check the JSON input for any incorrect values or formatting.

Integration

  • Combine with Get-Content to convert a JSON file into a PowerShell object.
  • Use Select-Object to filter the converted object based on specific properties.
  • Pipe the output to Out-File to save the converted object as a JSON or CSV file.
  • ConvertTo-Json: Converts a PowerShell object into a JSON string.
  • Newtonsoft.Json: A third-party module for extended JSON manipulation and serialization.