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

Time:09-09

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

CodePudding user response:

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)

CodePudding user response:

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"
  • Related