skip to Main Content

I have a JSON object that contains a JWT token. I would like to extract the claims from the token and put them into the JSON object, replacing the token. Here is my object:

{
  "id": 7,
  "time": "now",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiYm9iYnkiLCJjb2xvciI6ImJsdWUiLCJ0cmVlIjoiZWxtIn0K.9JCVXpkI6ICc5RnIsIiN1IzUIJiOicGbhJye"
}

The JWT contains these claims (base64 encoded in the middle field of the JWT, delimited by dots):

{
    "name": "bobby",
    "color": "blue",
    "tree": "elm"
}

How can I pull out the claims and put them into the JSON in place of the JWT token using jq?

2

Answers


  1. Chosen as BEST ANSWER

    Use the splits function to split the token on dots, the @base64d filter to base64 decode the data, and the fromjson filter to turn the string into JSON.

    The |= update operator can be used to assign the result back to the .token field.

    jq '.token |= ([splits("\.")][1] | @base64d | fromjson)' file.json
    

    Result:

    {
      "id": 7,
      "time": "now",
      "token": {
        "name": "bobby",
        "color": "blue",
        "tree": "elm"
      }
    }
    

  2. Split the value of .token at the dot into an array, take the second item, and use @base64d to decode base64, and fromjson to interpret the output as JSON:

    jq '.token |= ((./".")[1] | @base64d | fromjson)'
    
    {
      "id": 7,
      "time": "now",
      "token": {
        "name": "bobby",
        "color": "blue",
        "tree": "elm"
      }
    }
    

    Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search