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
Use the
splits
function to split the token on dots, the@base64d
filter to base64 decode the data, and thefromjson
filter to turn the string into JSON.The
|=
update operator can be used to assign the result back to the.token
field.Result:
Split the value of
.token
at the dot into an array, take the second item, and use@base64d
to decode base64, andfromjson
to interpret the output as JSON:Demo