PowerShell Script to Convert JSON to CSV Easily
Get-Content input.json | ConvertFrom-Json | Export-Csv output.csv -NoTypeInformation in PowerShell to convert a JSON file to CSV format.Examples
How to Think About It
ConvertFrom-Json. Then export these objects to CSV format using Export-Csv. This approach works because JSON objects map naturally to CSV rows and columns.Algorithm
Code
Get-Content input.json | ConvertFrom-Json | Export-Csv output.csv -NoTypeInformation
Write-Output "CSV file created as output.csv"Dry Run
Let's trace converting JSON array of two people to CSV
Read JSON file
[{"name":"Alice","age":30},{"name":"Bob","age":25}]
Convert JSON to objects
@{name=Alice; age=30}, @{name=Bob; age=25}
Export objects to CSV
name,age Alice,30 Bob,25
| Step | Data |
|---|---|
| 1 | [{"name":"Alice","age":30},{"name":"Bob","age":25}] |
| 2 | @{name=Alice; age=30}, @{name=Bob; age=25} |
| 3 | name,age Alice,30 Bob,25 |
Why This Works
Step 1: Read JSON content
The script reads the JSON text from a file using Get-Content, which loads the raw JSON string.
Step 2: Convert JSON to objects
ConvertFrom-Json parses the JSON string into PowerShell objects that can be manipulated or exported.
Step 3: Export to CSV
Export-Csv takes the objects and writes them as CSV rows and columns, with -NoTypeInformation to keep the file clean.
Alternative Approaches
$json = Get-Content input.json | ConvertFrom-Json
$csv = $json | ForEach-Object { "$($_.name),$($_.age)" }
$csv | Set-Content output.csv
Write-Output "CSV file created manually"$json = Get-Content input.json | ConvertFrom-Json
$json | ConvertTo-Csv -NoTypeInformation | Out-File output.csv
Write-Output "CSV file created using ConvertTo-Csv"Complexity: O(n) time, O(n) space
Time Complexity
The script processes each JSON object once to convert and export, so time grows linearly with the number of objects.
Space Complexity
Memory usage grows linearly with the JSON size as all objects are loaded into memory before exporting.
Which Approach is Fastest?
Using Export-Csv directly after ConvertFrom-Json is efficient and simple; manual parsing is slower and error-prone.
| Approach | Time | Space | Best For |
|---|---|---|---|
| ConvertFrom-Json + Export-Csv | O(n) | O(n) | General use, simple and fast |
| Manual parsing and writing | O(n) | O(n) | Custom CSV formats, small data |
| ConvertTo-Csv + Out-File | O(n) | O(n) | When needing CSV as string before saving |
-NoTypeInformation with Export-Csv to avoid extra type info lines in your CSV file.ConvertFrom-Json before exporting causes errors because raw JSON text cannot be exported directly.