I have the Json file called Services.json with following content:
{
"name":"Services",
"version":"1.2.0",
"description":"Customer Services"
}
I want to read this file and while reading if it finds "version" key then save respective value(1.2.0) into a variable using command line script
I tried something like this but it didn’t work.
@Echo off
for /f "tokens=1,2 delims=:{} " %%A in (Services.json) do (
If "%%~A"=="version" (
set version = "%%~b"
)
)
pause
4
Answers
I suggest to use a structure-aware tool like jq to get content from a JSON file.
It’s been asked before, but it’s easier for me to re-write it again that look it up.
— Revision since the JSON file is actually 1 line
rem Always verify against a test directory before applying to real data.
Read the data to
json
, remove all braces, processjson
as a comma-separated list of elements"name":"value"
Check whether the
name
is on the list; if so, assign thevalue
.You can parse your JSON file using PowerShell and set it as a variable in your batch file with
for /f..do
loop command like this example :This pure Batch solution get the values of all variables:
Output:
New method assuming that "the keyvalue pair is in a single line":