0
{
    "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%.
4
  • With a doublequote delimiter, the third token is a sequence of space colon space on the target line. Commented Sep 8, 2022 at 9:00
  • I am pretty new to this, can you please enlighten me about the correct use of delimiter and tokens and what should I use for this particular case? Commented Sep 8, 2022 at 9:07
  • Clearly you want the fourth token if using a doublequote as the delimiter. Commented Sep 8, 2022 at 9:10
  • Thank you so much. In scripting, I am not even a beginner(less than that). Can you please recommend me any/some good tutorials(paid/unpaid) to learn batch script and even VB script(I wanna learn that too). Commented Sep 8, 2022 at 9:26

2 Answers 2

1

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"
Sign up to request clarification or add additional context in comments.

Comments

0
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.