0

I have a .json file and want to extract the value for a certain key - but the key occurs multiple times (because the JSON contains a list of arrays). But I know that the value I am looking for starts with a certain prefix, so I wrote this:

for /f "tokens=1,2 delims=:, " %%a in (' find ":" ^< "myjson.json" ') do (
    if "%%~a"=="mykey" (
        set VALUE_I_WANT_TO_EXTRACT=%%~b
        echo b: %%~b
        echo var: %VALUE_I_WANT_TO_EXTRACT%
        IF "%VALUE_I_WANT_TO_EXTRACT:~0,8%"=="myprefix" (
            goto leave
        )
    )
)
:leave

prints:

b: myprefixvalue
var:
b: othervalue1
var: 
b: othervalue2
var:

When I REM out the line echo b: %%~b I get:

var: othervalue2
var: othervalue2
var: othervalue2

What happens here? And how do I get the value I am looking for?

Munchkin
  • 4,528
  • 7
  • 45
  • 93
  • An example of the input file would help to see. – Squashman Nov 21 '16 at 23:46
  • 1
    Use `setlocal EnableDelayedExpansion` at the beginning of your .cmd. And use `!VALUE_I_WANT_TO_EXTRACT!` instead of `%VAL...%` in the `for` loop body. – Dmitry Sokolov Nov 21 '16 at 23:53
  • @DmitrySokolov Great, this works! Can you explain why? – Munchkin Nov 22 '16 at 07:26
  • The immediate `%VAR%` expansion syntax expands the variable at *parsing time*, so when the entire line or `(`block`)` of code is read; to expand a variable during *execution time*, there is a feature called [delayed expansion](http://ss64.com/nt/delayedexpansion.html), which looks like `!VAR!` after having been enabled by a preceding `setlocal EnableDelayedExpansion`... – aschipfl Nov 22 '16 at 13:28
  • 2
    Possible duplicate of [Use a variable in a 'for' loop](http://stackoverflow.com/questions/6373307/use-a-variable-in-a-for-loop) – aschipfl Nov 22 '16 at 13:39

0 Answers0