windows 如何在批处理脚本中读取JSON数据

e7arh2l6  于 2022-11-26  发布在  Windows
关注(0)|答案(4)|浏览(608)

我有一个名为“Config.json”的JSON文件,看起来如下所示:
{ "RunEnvironment": "DEV"}
在同一目录下的批处理文件中,我想读取“RunEnvironment”元素的值。我的批处理脚本如下所示:
if [jsonElement] == 'DEV' ( :: do something )
谁能教我怎么做这个?

cyej8jka

cyej8jka1#

例如,在PowerShell中,您可以执行以下操作:

> If((Get-Content '.\Config.json'|ConvertFrom-Json).RunEnvironment -eq 'DEV'){"is DEV:Whatever"}
is DEV:Whatever

在cmd行上的主题上

> for /f "tokens=1,2 delims=:{} " %A in (Config.json) do @If "%~B"=="Dev" @Echo (%~A = %~B)
(RunEnvironment=DEV)

在批处理文件中

@Echo off
for /f "tokens=1,2 delims=:{} " %%A in (Config.json) do (
    If "%%~B"=="Dev" Echo (%%~A=%%~B^)
)

Echo (%%~A=%%~B^)可以被你计划做的任何事情所取代。

j13ufse2

j13ufse22#

如果您只需要在RunEnvironment的值为DEV的情况下执行特定命令,则这应该就是您所需要的全部内容,(来自batch-filecommand-line

"%__APPDIR__%FindStr.exe" /IRC:"\"RunEnvironment\":\ \ *\"DEV\"" "Config.json">NUL 2>&1&&Echo Your command here
  • 只需将Echo Your command here替换为您想要的命令。*
xzlaal3s

xzlaal3s3#

哟能这样做

@echo off 
set string={ "RunEnvironment": "DEV" }

for /f "tokens=3,5" %%a in ('echo %string%') do set d=%%~a 
if "%d%" == "DEV" echo %d%   
pause & goto :EOF
ahy6op9u

ahy6op9u4#

在批处理文件中:

@ECHO off

SET "FilenameForJsonFile=Config.json"
SET "FilenameForRunEnvironment=RunEnvironment.txt"

powershell -Command "Select-String -Pattern 'RunEnvironment\"\: \".*?\"' .\%FilenameForJsonFile% ^| ForEach-Object { $_.Matches.Value.substring(18,$_.Matches.Value.Length-19) }>%FilenameForRunEnvironment%

FOR /f "delims=" %%x IN (%FilenameForRunEnvironment%) DO SET JsonElement=%%x
       
IF %JsonElement%==DEV (ECHO development environment) ELSE (ECHO abc123 environment)

相关问题