Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding JSON and a base64-encoded value in a shell script

I have a JSON and I need to extract a base64-encoded value by particular key and decode it.

JSON has the following structure:

[
  {
    "LockIndex": 0,
    "Key": "Arul/key1",
    "Flags": 0,
    "Value": "MzAKCg==",
    "CreateIndex": 369,
    "ModifyIndex": 554
  }
]

In the above JSON, I need to extract only "Value":"MzAKCg==" and decode the base64-encoded "MzAKCg==" value. I would like to perform this using shell scripting.

Please assist.

like image 417
Arul Avatar asked Dec 01 '16 12:12

Arul


2 Answers

jq has recently added support for base64 encoding and decoding

https://stedolan.github.io/jq/manual/#Formatstringsandescaping

@base64:

The input is converted to base64 as specified by RFC 4648.

@base64d:

The inverse of @base64, input is decoded as specified by RFC 4648. Note: If the decoded string is not UTF-8, the results are undefined.

For your data, the command would be

jq -r 'map(.Value | @base64d)' < file.json

https://github.com/stedolan/jq/issues/47

It's not released yet, but you can install the latest development version to use it.

brew reinstall --HEAD jq

Once the next version of jq is released then you can switch back to the latest stable version.

like image 58
mpkuth Avatar answered Sep 28 '22 21:09

mpkuth


Using jq and base64:

jq -r '.[].Value' < file.json | base64 --decode
like image 37
Ruslan Osmanov Avatar answered Sep 28 '22 22:09

Ruslan Osmanov