PowerShell by Patrik

Pretty-Print JSON Strings in PowerShell

To display JSON in a structured and readable format directly in PowerShell, you can pipe a JSON string through ConvertFrom-Json and then ConvertTo-Json with an appropriate -Depth parameter. This allows you to avoid using intermediary variables and outputs neatly formatted JSON directly to the console.

Example:

'{"name":"John","age":30,"address":{"street":"123 Main St","city":"Anytown"},"phones":["123-4567","987-6543"]}' 
| ConvertFrom-Json 
| ConvertTo-Json -Depth 10

Explanation:

  • ConvertFrom-Json parses the raw JSON string into a PowerShell object.
  • ConvertTo-Json re-serializes the object with proper indentation.
  • The -Depth parameter ensures that nested objects are fully expanded in the output.

This approach is useful for quickly inspecting JSON structures without needing temporary variables or additional tools.

PowerShell
JSON
scripting

Comments