读取json文件并使用命令行脚本设置变量

uqdfh47h  于 2022-12-20  发布在  其他
关注(0)|答案(4)|浏览(126)

我有一个名为Services.json的Json文件,其中包含以下内容:

{
    "name":"Services",
    "version":"1.2.0",
    "description":"Customer Services"
}

我想读取此文件,如果在阅读时发现“版本”键,则使用命令行脚本将相应值(1.2.0)保存到变量中
我试过这样的方法,但没有用。

@Echo off
for /f "tokens=1,2 delims=:{} " %%A in (Services.json) do (
    If "%%~A"=="version" (
      set version = "%%~b"
    )
)
pause
5lwkijsr

5lwkijsr1#

您可以使用PowerShell解析JSON文件,并使用for /f..do循环命令将其设置为批处理文件中的变量,如下所示:

@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
lvmkulzt

lvmkulzt2#

@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

以前有人问过,但对我来说,查一查,重写一遍更容易。
---修订,因为JSON文件实际上只有1行

@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_2.txt"

SET /p json=<"%filename1%"
SET "json=%json:{=%"
SET "json=%json:}=%"
FOR %%e IN (%json%) DO (
 FOR /f "tokens=1,2delims=:" %%b in ("%%e") do FOR %%y IN (version description name) DO IF /i "%%y"==%%b SET "%%y=%%~c"
)
ECHO version=%version%
ECHO name=%name%
ECHO description=%description%

GOTO :EOF

rem在应用于真实的数据之前,始终根据测试目录进行验证。
将数据读取到json,删除所有大括号,将json处理为逗号分隔的元素列表"name":"value"
检查name是否在列表中;如果是,则指定value

8hhllhi2

8hhllhi23#

此纯批处理解决方案获取 * 所有 * 变量的值:

@echo off
setlocal EnableDelayedExpansion

rem Get variables
set "var="
for /F "tokens=1* delims=:{} " %%a in (Services.json) do (
   for %%c in (%%a %%b) do (
      if not defined var (set "var=%%~c") else set "!var!=%%~c" & set "var="
   )
)

rem Show values
echo name=%name%
echo version=%version%
echo description=%description%

输出:

name=Services
version=1.2.0
description=Customer Services
    • 新方法**假设 "键值对在一行中"
@echo off
setlocal

rem Get variables
set /P "json=" < Services.json
set "json=%json:{=%"
set "json=%json:}=%"
set "json=%json:":"==%"
set %json:,= & set %

rem Show values
echo name=%name%
echo version=%version%
echo description=%description%
gr8qqesn

gr8qqesn4#

我建议使用jq这样的结构感知工具从JSON文件中获取内容。

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

相关问题