johnny_k
johnny_k

Reputation: 1

Echo the value of a field in a json file using batch script

{
    "fields" : {
        "field_10061" : 24,   
        "field_10101" : "GB"
    }
}

I have this .json file named storage.json located in C:\files\storage.json and the contents of storage.json is as above:-

I want to create a batch file that stores the value of "field_10101" which is "GB" in a variable and echo it. I have tried this command below but its not working.

set LOC=C:\files\storage.json

for /f  delims^=^"^ tokens^=3 %%A in ('findstr /R "field_10101" %LOC%') do set new=%%A

echo %new%.

Upvotes: 0

Views: 541

Answers (2)

Reino
Reino

Reputation: 3443

You're dealing with JSON, so please use a proper JSON-parser!

With :

FOR /F "delims=" %%A IN ('
  xidel -s "C:\files\storage.json" -e "$json/fields/field_10101"
') DO SET "new=%%A"

Or with --output-format=cmd and the dot-notation instead of the XPath-notation:

FOR /F "delims=" %%A IN ('
  xidel -s "C:\files\storage.json" -e "new:=($json).fields.field_10101" --output-format^=cmd
') DO %%A

Or with :

FOR /F "delims=" %%A IN ('
  jq -r ".fields.field_10101" "C:\files\storage.json"
') DO SET "new=%%A"

Upvotes: 1

Yury Slinkin
Yury Slinkin

Reputation: 26

set LOC=C:\files\storage.json
for /f  delims^=^"^ tokens^=3 %%A in ('findstr /R "field_10101" %LOC%') do set new=%%A
call :getvalue %new%
echo %value%
goto exit
:getvalue
set "value=%~3"
goto exit
:exit

maybay use real json parsers? (as universal method that work with any json files)

vbs/wsh/jscript (native)             //maybay dll files?
powershell (native)                  //maybay in -Command "" and ignore Get-ExecutionPolicy ?
base64-encoded "internal components" //echo BASE64STRING... >tofile... ... certutil (native)

Upvotes: 0

Related Questions