How to Read a Specific Value from a JSON File in Batch Script
Configuration files, API response payloads, and modern datastores heavily utilize JavaScript Object Notation (JSON). Automating IT workflows often requires extracting precisely one piece of data from these hierarchical files, like an Environment tag, an IP_Address, or a Version number. Because standard Batch parsing (findstr or for /f) relies entirely on fragile string splitting instead of logical structure syntax, you must approach this task intelligently.
In this guide, we will demonstrate how to query and extract a specific value from a JSON file.
Method 1: The PowerShell Bridge (Industry Standard)
The most robust way to query a JSON file is to deserialize it into an object using PowerShell's ConvertFrom-Json cmdlet. This effectively treats the JSON schema as an object hierarchy.
Setup: A Sample config.json
{
"application": {
"name": "IntranetPortal",
"version": "12.4.0",
"database": {
"host": "192.168.1.50",
"port": 5432
}
}
}
Implementation Script
@echo off
setlocal enabledelayedexpansion
:: Define the target JSON file
set "jsonFile=config.json"
if not exist "%jsonFile%" (
echo [ERROR] "%jsonFile%" not found.
pause
exit /b 1
)
echo Extracting database host from "%jsonFile%"...
echo.
:: 1. Read JSON file
:: 2. Convert to PowerShell Object
:: 3. Target the specific nested property (application.database.host)
set "dbHost="
for /f "usebackq tokens=*" %%A in (`powershell -NoProfile -Command "(Get-Content -Path '%jsonFile%' -Raw | ConvertFrom-Json).application.database.host"`) do (
set "dbHost=%%A"
)
:: Validate Output
if defined dbHost (
echo Found Database Host: !dbHost!
) else (
echo [ERROR] Property not found or empty.
pause
exit /b 1
)
endlocal
pause
exit /b 0
Method 2: Using the Lightweight jq CLI Utility
If invoking PowerShell introduces too much execution latency (startup overhead), or if your JSON is exceptionally large, the fastest enterprise solution is downloading the lightweight, open-source jq.exe binary. It is explicitly designed for lightning-fast command-line JSON parsing.
Implementation Script
Assuming jq.exe is located in your script folder or system PATH:
@echo off
setlocal enabledelayedexpansion
set "jsonFile=config.json"
:: 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] "%jsonFile%" not found.
pause
exit /b 1
)
:: Use jq's filter syntax: .application.database.port
:: The -r flag prints raw strings without quotes
set "dbPort="
for /f "tokens=*" %%A in ('jq.exe -r ".application.database.port" "%jsonFile%" 2^>nul') do (
set "dbPort=%%A"
)
if not defined dbPort (
echo [ERROR] Property not found or JSON parse error.
pause
exit /b 1
)
echo The database port is: !dbPort!
endlocal
pause
exit /b 0
Why Read Values from JSON Files?
- Centralized Configuration: Storing a single
appsettings.jsonfile that controls dozens of environment variables identically across C#, Node.js, and your Batch deployment scripts. - API Verification: Polling an endpoint with
curl -o response.json, extracting the"status": "success"flag, and aborting the batch script if the service indicates failure. - Cloud State Detection: Triggering
aws ec2 describe-instances > state.json, and targeting the"InstanceId"node before executing the termination procedure.
Important Considerations
- Arrays vs Objects: If your JSON starts with an Array (
[ { ... } ]), you must query it using an index. In PowerShell, this looks like.application.servers[0].host. Injq.exe, it's.[0].application.servers[0].host. - Performance Trade-offs: The
jqimplementation reads much shorter syntax and relies entirely on standard I/O redirection, whereas PowerShell converts the whole file to .NET memory before addressing the property. For large files or repeated calls,jq.exeis significantly faster. - Invalid JSON Syntax: If the
.jsonfile contains a syntax error (like a missing comma or an unescaped string), neither PowerShell norjqwill return a value. They will output a parse exception. Ensure your JSON is valid.
Conclusion
Reading specific values directly from a complex JSON file liberates your Batch scripts from simple hardcoded text strings. By utilizing PowerShell's object conversion or standardizing on the blazing-fast jq.exe binary, you can reliably traverse massive nested configuration hierarchies, fetching the exact parameters you need dynamically at runtime.