Home > Software design >  jq - decode json value in flow
jq - decode json value in flow

Time:04-08

I am need to decode the authorization value from apache in flow and replace the value with the username , returning the modified json.

original Json:

{ "time":"2022-04-07T12:53:39.302 0300", 
.... 
"user":"Basic c2RwC2ZhcmZZc3Q6c2RfX2ZhcmVhz3Q=" }

I want to get json:

{ "time":"2022-04-07T12:53:39.302 0300", 
.... 
"user":"<login>" }

Decoded value here is <username>:<password>

I'm trying to use the jq utility for this

stdin> | jq -r  '.user | gsub ("Basic "; "") | @base64d | gsub ("^.*:"; "")'

But jq returns the value itself, not the modified json. Also, I get an error if json value (user) isn't base64 "user":"-"

jq: error (at <stdin>:1): string ("-") is not valid base64 data

How can I get the full modified json and avoid modification if the user value does not contain "Basic" ?

CodePudding user response:

Use if ... then ... else ... end to implement different behaviours depending on a value.

jq '.user |= if startswith("Basic ")
             then .[6:] | @base64d
             else . end
  ' file.json
  • Related