0

I got this simple code which read an array in json and place values in independent variables %1%, %2%, %3% and %4% instead of that I would like to place these values inside an array myarray[1], myarray[2], myarray[3] and myarray[4], how could I modifiy the code to achieve this goal?

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 "%"

from this stackoverflow answer : https://stackoverflow.com/a/36375415/876637

cz3ch
  • 409
  • 2
  • 11

2 Answers2

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

Output:

myarray[1]=10%
myarray[2]=20%
myarray[3]=30%
myarray[4]=40%
Aacini
  • 65,180
  • 12
  • 72
  • 108
0

It is also possible to use following code:

@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

Note: There are two characters after {} in second line: a horizontal tab and a space character.

The output is:

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

The file stats.json can contain with this code a single line with

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

or multiple lines like

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

It does not matter if file stats.json contains spaces/tabs or not.

It also does not matter if a line contains one, two, three or all four variable/value pairs.

Mofi
  • 46,139
  • 17
  • 80
  • 143