PowerShell Script to Convert CSV to JSON Easily
Import-Csv 'input.csv' | ConvertTo-Json | Set-Content 'output.json' in PowerShell to convert a CSV file to JSON format quickly.Examples
How to Think About It
Import-Csv which converts each row into an object. Then use ConvertTo-Json to transform these objects into JSON format. Finally, save the JSON string to a file with Set-Content.Algorithm
Code
Import-Csv 'input.csv' | ConvertTo-Json | Set-Content 'output.json' # To see the JSON output on screen: Import-Csv 'input.csv' | ConvertTo-Json | Write-Output
Dry Run
Let's trace converting a CSV with two rows: Name,Age\nAlice,30\nBob,25 through the code.
Import CSV
Import-Csv reads the CSV and creates an array of objects: [{Name: 'Alice', Age: '30'}, {Name: 'Bob', Age: '25'}]
Convert to JSON
ConvertTo-Json converts the array of objects into a JSON string representing the array.
Write JSON to file
Set-Content writes the JSON string to 'output.json' file.
| Step | Data |
|---|---|
| Import-Csv | [{Name: 'Alice', Age: '30'}, {Name: 'Bob', Age: '25'}] |
| ConvertTo-Json | [{"Name":"Alice","Age":"30"},{"Name":"Bob","Age":"25"}] |
| Set-Content | Writes JSON string to output.json |
Why This Works
Step 1: Import-Csv reads CSV
The Import-Csv cmdlet reads the CSV file and converts each row into a PowerShell object with properties matching the CSV headers.
Step 2: ConvertTo-Json transforms objects
ConvertTo-Json takes the array of objects and converts it into a JSON formatted string representing the data.
Step 3: Set-Content saves JSON
Set-Content writes the JSON string to a file, creating or overwriting the output JSON file.
Alternative Approaches
Import-Csv 'input.csv' | ConvertTo-Json | Out-File 'output.json' -Encoding utf8
$csv = Get-Content 'input.csv' | ConvertFrom-Csv $csv | ConvertTo-Json | Set-Content 'output.json'
Import-Csv 'input.csv' | ConvertTo-Json -Depth 3 | Set-Content 'output.json'
Complexity: O(n) time, O(n) space
Time Complexity
The script reads each CSV row once and converts it to JSON, so time grows linearly with the number of rows.
Space Complexity
Memory usage grows linearly with the number of CSV rows because all data is loaded into memory before conversion.
Which Approach is Fastest?
Using Import-Csv piped directly to ConvertTo-Json is fastest and simplest; alternatives add overhead or complexity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Import-Csv | ConvertTo-Json | Set-Content | O(n) | O(n) | Simple, direct CSV to JSON conversion |
| Get-Content + ConvertFrom-Csv + ConvertTo-Json | O(n) | O(n) | When preprocessing CSV lines is needed |
| ConvertTo-Json with -Depth parameter | O(n) | O(n) | Handling nested or complex CSV data |
ConvertTo-Json -Depth 3 if your CSV data has nested objects to avoid truncated JSON output.Import-Csv and trying to convert raw CSV text directly to JSON causes errors.