Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and set a variable on the Windows command line from a .json file

I have this little config.json:

{
    "version":"0.2.2",
    "test":true
}

I'd like to read this file and set variables in the window command line corresponding the keys and values from the json file, perhaps something like this pseudo code:

for /f %%A in (config.json) do (

    SET key = value
)

echo %VERSION%
echo %TEST%

How would I do that?

like image 505
Kriem Avatar asked Oct 07 '13 12:10

Kriem


1 Answers

This solves the question as posed:

@echo off
setlocal EnableDelayedExpansion
set c=0
for /f "tokens=2 delims=:, " %%a in (' find ":" ^< "config.json" ') do (
   set /a c+=1
   set val[!c!]=%%~a
)
for /L %%b in (1,1,!c!) do echo !val[%%b]!
pause

This version will output version = 0.2.2 and test = true
The only change is in line 6

@echo off
setlocal EnableDelayedExpansion
set c=0
for /f "tokens=1,2 delims=:, " %%a in (' find ":" ^< "config.json" ') do (
   set /a c+=1
   set val[!c!]=%%~a = %%~b
)
for /L %%b in (1,1,!c!) do echo !val[%%b]!
pause

This solves the next format request: variable-name=value

@echo off
for /f "tokens=1,2 delims=:, " %%a in (' find ":" ^< "config.json" ') do (
   set "%%~a=%%~b"
)
set
pause

The request from Feb 2016 can be solved with this, assuming the file looks like below:

 {
 location : "C:\\Test Folder"
 }

Batch script below

@echo off
for /f "tokens=1,2,*" %%a in (' find ":" ^< "config.json" ') do echo "%%~c"
pause
like image 95
foxidrive Avatar answered Nov 03 '22 00:11

foxidrive