How to Convert CSV to JSON in Batch Script
Converting a flat, tabular CSV (Comma-Separated Values) file into JSON (JavaScript Object Notation) is essential when preparing corporate data for modern web APIs or NoSQL databases. Because JSON requires structured arrays and key-value mapping (which pure Batch scripts are famously terrible at generating without syntax errors), a PowerShell bridge is the undisputed best practice.
In this guide, we will demonstrate how to elegantly convert a CSV file to a formatted JSON payload from a Batch script.
The Strategy: The PowerShell Bridge
- Identify the source
.csvfile containing headers on the first row. - Use PowerShell's
Import-Csvcmdlet to automatically parse the rows and headers into objects. - Use the
ConvertTo-Jsoncmdlet to serialize those objects into a JSON structure. - Write the resulting JSON to a new
.jsonfile.
Setup: A Sample CSV File
To test the script, create a sample CSV file named inventory.csv:
ItemCode,Description,Quantity,Price
A001,Laptop Stand,45,29.99
B002,Optical Mouse,120,15.50
C003,Mechanical Keyboard,30,89.00
Implementation Script
@echo off
setlocal enabledelayedexpansion
:: Define file paths
set "csvFile=C:\Temp\inventory.csv"
set "jsonFile=C:\Temp\inventory.json"
echo Processing CSV File: "%csvFile%"...
if not exist "%csvFile%" (
echo [ERROR] The CSV file "%csvFile%" was not found.
pause
exit /b 1
)
echo Converting to JSON format...
:: Execute via PowerShell bridge
:: 1. Import the CSV
:: 2. Convert to JSON (Depth 2 is usually sufficient for flat arrays)
:: 3. Set-Content writes it securely, forcing UTF-8 encoding
powershell -NoProfile -Command ^
"Import-Csv -Path '%csvFile%' | " ^
"ConvertTo-Json -Depth 2 | " ^
"Set-Content -Path '%jsonFile%' -Encoding UTF8"
:: Capture the exit code immediately
set "psResult=!errorlevel!"
if !psResult! neq 0 (
echo [ERROR] PowerShell conversion failed with exit code !psResult!.
pause
exit /b 1
)
:: Verify the output file was created
if not exist "%jsonFile%" (
echo [ERROR] Output file "%jsonFile%" was not created.
pause
exit /b 1
)
echo.
echo ==========================================
echo CONVERSION SUCCESSFUL
echo Output saved at: "%jsonFile%"
echo ==========================================
endlocal
pause
exit /b 0
Advanced: Compressing Result JSON (Minified Output)
By default, PowerShell produces beautifully formatted, human-readable JSON. However, if you are planning to send this payload via an API webhook, you usually want to minimize its size by removing all spaces and line breaks. You can achieve this using the -Compress flag.
@echo off
setlocal enabledelayedexpansion
set "csvFile=data.csv"
set "jsonFile=data.json"
if not exist "%csvFile%" (
echo [ERROR] The CSV file "%csvFile%" was not found.
pause
exit /b 1
)
echo Converting to minified JSON...
:: Use the -Compress parameter in ConvertTo-Json
powershell -NoProfile -Command ^
"Import-Csv -Path '%csvFile%' | " ^
"ConvertTo-Json -Compress | " ^
"Set-Content -Path '%jsonFile%' -Encoding UTF8"
:: Capture the exit code immediately
set "psResult=!errorlevel!"
if !psResult! neq 0 (
echo [ERROR] PowerShell conversion failed with exit code !psResult!.
pause
exit /b 1
)
if not exist "%jsonFile%" (
echo [ERROR] Output file "%jsonFile%" was not created.
pause
exit /b 1
)
echo [SUCCESS] Created minified JSON at "%jsonFile%".
endlocal
pause
exit /b 0
Why Convert CSV to JSON?
- API Integrations: Taking an Excel export of user accounts (CSV) and automatically converting it to JSON so your batch script can
curl POSTthem into an HR system. - Web Dashboards: A nightly script that dumps a database query to CSV, converts it to JSON, and SFTPs it to a web server for frontend JavaScript charting libraries.
- Modernizing Datastores: Shifting away from legacy flat-file databases to NoSQL solutions like MongoDB, which ingest JSON arrays natively.
Important Considerations
- Data Types: CSV files have no concept of integers or booleans; everything is just a string of text.
ConvertTo-Jsonwill therefore output every value inside double-quotes (e.g.,"Quantity": "45"instead of"Quantity": 45). If strict data typing is required by your API, you must explicitly cast those properties in PowerShell before converting. - Delimiters: The PowerShell
Import-Csvcmdlet assumes commas. If you are handling a European semicolon-delimited file, you must add-Delimiter ';'to theImport-Csvcall. - Encoding Issues: It is critical to enforce UTF-8 across the output cmdlet. Otherwise, PowerShell defaults to its system encoding (often UTF-16 in older environments), which web APIs typically reject with
400 Bad Requesterrors.
Conclusion
Converting rigid, tabular CSV data into flexible, web-ready JSON structure is a core data-engineering workflow. While Batch scripts lack native array logic, bridging this operation through PowerShell creates a flawless conversion mechanism in just one succinct line of code. This ensures your data seamlessly interfaces with the modern, JSON-driven web.