jsonbatch-file

Extract an information from a JSON file with jq and set the information in a variable


I want to extract an information from a JSON file called blablabla.json which look like this:

{
  "token": {
   "issued_at": "2018-11-04T23:35:07Z",
   "expires_at": "2018-11-05T00:35:07Z",
   "user": {
    "id": "ide",
    "name": "ide"
   }
  }
}

I want to get the "expires_at" date to compare it with the current date. To do that, I use this:

type blablabla.json|jq .token".expires_at"

It works, but I don't know how to set it to a variable. I try somethings like:

SET date=type blablabla.json|jq .token".expires_at"

but it does nothing. Do you have an idea?

Thank you very much.


Solution

  • Generally, you'd use a For /F loop:

    @Echo Off
    For /F "Delims=" %%A In ('type blablabla.json^|jq .token".expires_at"'
    ) Do Set "Expiry=%%~A"
    

    Where your result can be accessed using the variable, %Expiry%. (You wouldn't set a variable to the name of an important existing system variable).

    As for checking it against the current date, you'd need to find a method of doing that as both dates would be strings, not date objects. That is outside of the scope of this question.