Home > front end >  Read the json file and set a variable using command line script
Read the json file and set a variable using command line script

Time:12-16

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

CodePudding user response:

@ECHO OFF
SETLOCAL
rem The following settings for the source directory and filename are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "filename1=%sourcedir%\Q74814659.txt"

FOR /f "usebackqtokens=1,2delims=:, " %%b IN ("%filename1%") DO IF %%b=="version" SET "version=%%~c"
ECHO version=%version%

GOTO :EOF

It's been asked before, but it's easier for me to re-write it again that look it up.

CodePudding user response:

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 :


@echo off
Title Get Version from Services.json using PowerShell with a batch file
Set PSCMD=Powershell -C "$(GC Services.json | ConvertFrom-Json).version"
@for /f %%a in ('%PSCMD%') do set "Ver=%%a"
echo Version=%Ver%
pause

CodePudding user response:

I suggest to use a structure-aware tool like jq to get content from a JSON file.

$version = (jq -r '.version' Services.json)
  • Related