How to Write a Value to a JSON File in Batch Script
Updating configurations, modifying state files for deployment pipelines, and managing API payloads often requires injecting dynamic script variables into a structured JSON (JavaScript Object Notation) file. Native Batch cannot structurally manipulate JSON strings. If you attempt to rebuild strings entirely with echo commands, escaping internal double-quotes becomes a nightmare that usually results in invalid JSON parameters.
In this guide, we will demonstrate how to correctly write or modify values inside a JSON file utilizing PowerShell automation.
The Strategy: The Object-Modification Approach
- Load the original
.jsonfile into memory by casting it as a PowerShell Object. - Traverse down to the precise nested property you wish to update.
- Assign the new value (e.g., updating
{ "status": "running" }tostopped). - Re-serialize the object using
ConvertTo-Json. - Overwrite the original
.jsonfile with the updated structure.
Setup: A Sample appsettings.json
{
"system": "MainServer",
"maintenanceMode": false,
"config": {
"logLevel": "INFO",
"maxConnections": 50
}
}
Implementation Script (PowerShell Bridge)
@echo off
setlocal enabledelayedexpansion
:: Define Paths
set "jsonFile=C:\App\appsettings.json"
:: Define Variables to Write
set "newStatus=true"
set "newLogLevel=DEBUG"
echo Validating file existence...
if not exist "%jsonFile%" (
echo [ERROR] JSON file "%jsonFile%" missing!
pause
exit /b 1
)
echo Updating Configuration Parameters...
:: 1. Read the JSON into an object ($json)
:: 2. Target the exact node and assign the new value
:: 3. Convert back to JSON (Depth 10 safely handles deep nesting)
:: 4. Write string safely back to disk (UTF-8 encoding)
powershell -NoProfile -Command ^
"$json = Get-Content -Path '%jsonFile%' -Raw | ConvertFrom-Json; " ^
"$json.maintenanceMode = $%newStatus%; " ^
"$json.config.logLevel = '%newLogLevel%'; " ^
"$json | ConvertTo-Json -Depth 10 | Set-Content -Path '%jsonFile%' -Encoding UTF8"
:: Capture the exit code immediately
set "psResult=!errorlevel!"
if !psResult! equ 0 (
echo.
echo ==========================================
echo JSON UPDATED SUCCESSFULLY:
echo maintenanceMode -^> %newStatus%
echo logLevel -^> %newLogLevel%
echo ==========================================
) else (
echo.
echo [ERROR] Failed to rewrite JSON with exit code !psResult!.
pause
exit /b 1
)
endlocal
pause
exit /b 0
Understanding the Property Assignment
Notice the syntax difference when assigning variables based on their designated JSON Type:
- Boolean: assigned using
$trueor$falsedirectly without quotes ($json.maintenanceMode = $true). - String: assigned using surrounding single quotes so they translate back to JSON double quotes natively (
$json.config.logLevel = 'DEBUG'). - Integer: assigned plainly (
$json.config.maxConnections = 100).
The jq Utility Alternative
If you have downloaded the lightweight jq.exe command-line utility, writing to JSON without the overhead of PowerShell is remarkably efficient. However, because jq writes specifically to an output stream, you must use a temporary file to prevent zeroing out the source file during redirection.
@echo off
setlocal enabledelayedexpansion
set "jsonFile=appsettings.json"
set "tmpFile=%TEMP%\jq_tmp.json"
set "newMode=DEBUG"
:: Verify jq is installed
where jq >nul 2>nul
if !errorlevel! neq 0 (
echo [ERROR] jq.exe is not installed or not in PATH.
pause
exit /b 1
)
:: Verify the JSON file exists
if not exist "%jsonFile%" (
echo [ERROR] JSON file "%jsonFile%" missing!
pause
exit /b 1
)
:: Modify the log level and write to temp file
:: The .config.logLevel flag targets the exact node
jq.exe ".config.logLevel = \"%newMode%\"" "%jsonFile%" > "%tmpFile%"
:: Capture the exit code immediately
set "jqResult=!errorlevel!"
if !jqResult! neq 0 (
echo [ERROR] jq failed with exit code !jqResult!.
del "%tmpFile%" 2>nul
pause
exit /b 1
)
:: Replace original with updated file
move /y "%tmpFile%" "%jsonFile%" >nul
if !errorlevel! neq 0 (
echo [ERROR] Failed to replace the original JSON file.
pause
exit /b 1
)
echo [SUCCESS] Values updated using jq.
endlocal
pause
exit /b 0
Why Write to JSON from Batch?
- Deployment Toggles: Running a
go_live.batscript that simultaneously updates IIS application pools, then writes"maintenanceMode": falseinto the web configuration JSON. - API Payloads: Modifying a static
request.jsontemplate with today's dynamically generated%DATE%timestamp before sending it to an AWS endpoint viacurl. - State Flags: Logging execution results generated entirely within Batch logic directly into structured NoSQL databases via a JSON file stream.
Important Considerations
- Depth Limitation: PowerShell's
ConvertTo-Jsondefaults to aDepthof 2. If your JSON structure is nested three or four arrays deep, the deeper nodes will be corrupted into@{Name=Value}string representations. Always set-Depth 10or higher to prevent corruption on complex files. - Formatting Loss: Serializing back to JSON strips any
.jsonfile of its original line spacing or manual comment annotations (// Note:). The entire file will emerge perfectly valid, but formatted rigidly by the serializer. - Encoding: If you omit
-Encoding UTF8in the output cmdlet, foreign characters will be destroyed, altering the file content significantly.
Conclusion
Dynamically injecting specific values into an active JSON configuration file ensures modern IT workflows are tightly bound with surrounding infrastructure. By casting the raw text into standard objects directly via PowerShell or seamlessly running jq updates, you confidently edit sophisticated hierarchies with zero risk of structural parsing errors.