I am calling a curl command in a batch file. The request gives me a JSON response. I store that JSON response in the file. I want to know how do I parse this JSON and fetch a specific attributes?
test.bat
%comspec% /c curl -L -c cookie -b cookie -X POST -H "Accept: application/json" -s -d "{\"id\":\"123456789\",\"part\":\"part\",\"duration\":1400}" https://abcd.com > MyIP.txt
set /p string1=<MyIP.txt
Above works fine and store the JSON in a file. A dummy response looks like the following:
{"aki":"abcd", "assumed":"cdef", "expiration":12345, "sa":"temp/abcdefgh", "st":"abcd+/00'nget"}
I need to get 'aki' and 'sa' variables from this response and store them to an another file.
I tried one met honed in the thread you shared, but the output is coming as empty:
This is exactly the reason why it's inadvisable to do this in pure cmd
/Batch without the proper tools.
While the code and JSON in your comment does work...
ECHO %other% %year% %value% %time%
1234 2016 str 05:01
...one of the things that will get you into trouble is the single quote within your original JSON response ("abcd+/00'nget"
). You'll have to escape all the necessary characters to make this work. A tool like xidel that properly handles JSON can show you:
ECHO {"aki":"abcd","assumed":"cdef","expiration":12345,"sa":"temp/abcdefgh","st":"abcd+/00'nget"} | ^
xidel - -se "string:=$json" --output-format=cmd
SET string={^"aki^": ^"abcd^"^, ^"assumed^": ^"cdef^"^, ^"expiration^": 12345^, ^"sa^": ^"temp/abcdefgh^"^, ^"st^": ^"abcd+/00'nget^"}
So the following could work:
SET string={^"aki^": ^"abcd^"^, ^"assumed^": ^"cdef^"^, ^"expiration^": 12345^, ^"sa^": ^"temp/abcdefgh^"^, ^"st^": ^"abcd+/00'nget^"}
SET string=%string:"=%
SET "string=%string:~1,-1%"
SET "string=%string:: ==%"
SET "%string:, =" & set "%"
ECHO %aki% %sa%
abcd temp/abcdefgh
BUT instead I would recommend using xidel right from the start:
xidel -s ^
-H "Cookie: [...]" -H "Accept: application/json" ^
-d "{{\"id\":\"123456789\",\"part\":\"part\",\"duration\":1400}}" ^
https://abcd.com ^
-e "$json" -e "$json/(aki,sa)"
{
"aki": "abcd",
"assumed": "cdef",
"expiration": 12345,
"sa": "temp/abcdefgh",
"st": "abcd+/00'nget"
}
abcd
temp/abcdefgh
(not 100% sure as I can't test this obviously)