我得到了这个简单的代码,该代码读取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
答案 0 :(得分: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%
答案 1 :(得分: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
是否包含空格/制表符都没关系。
一行包含一个,两个,三个或全部四个变量/值对也没关系。