将简单JSON放入批处理数组中

问题描述 投票:0回答:2

我得到了这个简单的代码,它读取json中的数组并将值放在自变量%1%,%2%,%3%和%4%中,而不是我想将这些值放在数组myarray [1]中, myarray [2],myarray [3]和myarray [4],我怎么能修改代码来实现这个目标?

rem Load stats for exemple do set stats={ 1: "10%", 2: "20%", 3: "30%", 4: "40%" }
for /f "delims=" %%x in (stats.json) do set stats=%%x
rem Remove quotes
set stats=%stats:"=%
rem Remove braces
set "stats=%stats:~2,-2%"
rem Change colon+space by equal-sign
set "stats=%stats:: ==%"
echo %stats%
rem Separate parts at comma into individual assignments
set "%stats:, =" & set "%"

从这个stackoverflow答案:https://stackoverflow.com/a/36375415/876637

json batch-file
2个回答
1
投票
@echo off
setlocal EnableDelayedExpansion

rem Load stats for exemple do set stats={ 1: "10%", 2: "20%", 3: "30%", 4: "40%" }
for /f "delims=" %%x in (stats.json) do set stats=%%x
rem Remove quotes
set stats=%stats:"=%
rem Remove braces
set "stats=%stats:~2,-2%"
rem Change colon+space by right square bracket + equal-sign
set "stats=%stats:: =]=%"
rem Separate parts at comma into individual assignments
set "myarray[%stats:, =" & set "myarray[%"

SET myarray

输出:

myarray[1]=10%
myarray[2]=20%
myarray[3]=30%
myarray[4]=40%

0
投票

也可以使用以下代码:

@echo off
for /F "usebackq tokens=1-8 delims=,:{}  " %%A in ("stats.json") do (
    if not "%%~A" == "" if not "%%~B" == "" set "myarray[%%A]=%%~B"
    if not "%%~C" == "" if not "%%~D" == "" set "myarray[%%C]=%%~D"
    if not "%%~E" == "" if not "%%~F" == "" set "myarray[%%E]=%%~F"
    if not "%%~G" == "" if not "%%~H" == "" set "myarray[%%G]=%%~H"
)
set myarray

注意:{}在第二行后面有两个字符:水平制表符和空格字符。

输出是:

myarray[1]=10%
myarray[2]=20%
myarray[3]=30%
myarray[4]=40%

文件stats.json可以包含此代码的单行

{ 1: "10%", 2: "20%", 3: "30%", 4: "40%" }

或多行如

{
    1: "10%",
    2: "20%",
    3: "30%",
    4: "40%"
}

文件stats.json是否包含空格/制表符并不重要。

如果一行包含一个,两个,三个或所有四个变量/值对也无关紧要。

© www.soinside.com 2019 - 2024. All rights reserved.