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 not recommended to do this in cmd / batch-file without the proper tools.
While the code and JSON in your comment does work...
C:\>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. The JSON-parser xidel, with the output-format set to "cmd", does this for you:
C:\>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 batch-file snippet should 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%
But I would recommend using Xidel right from the start, because it could (probably) do it all for you, while skipping the whole escape-characters issue:
C:\>xidel -s^
-H "Cookie: [...]" -H "Accept: application/json"^
-d "{serialize({'id':'123456789','part':'part','duration':1400},{'method':'json'})}"^
"https://abcd.com"^
-e "$json,$json/(aki,sa)"
{
"aki": "abcd",
"assumed": "cdef",
"expiration": 12345,
"sa": "temp/abcdefgh",
"st": "abcd+/00'nget"
}
abcd
temp/abcdefgh