解码 JSON 和 shell 脚本中的 base64 编码值

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

我有一个 JSON,我需要通过特定密钥提取 base64 编码值并对其进行解码。

JSON 具有以下结构:

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

在上面的JSON中,我只需要提取"Value":"MzAKCg=="并解码base64编码的"MzAKCg=="值。我想使用 shell 脚本来执行此操作。

请协助。

使用jq and base64

jq -r '.[].Value' < file.json | base64 --decode

如果此 JSON 始终具有相同的结构,您可以使用 cut -d 并稍后解码该值,例如:

$echo "Value": "MzAKCg==" | cut -d ":" -f 2 | base64 -D

30

jq最近增加了对base64编码和解码的支持

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.

对于您的数据,命令为

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

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

尚未发布,但您可以安装最新的开发版使用。

brew reinstall --HEAD jq

下一个版本的 jq 发布后,您可以切换回最新的稳定版本。

:

xidel -s input.json -e '$json()/binary-to-string(base64Binary(Value))'

xidel -s input.json -e 'binary-to-string(base64Binary($json//Value))'

这对我有用:curl --silent localhost:8500/v1/kv/key1 | jq -r '.[0].Value | @base64d'

使用内置的 jq base64 解码器:

echo '{"val" : "MzAKCg=="}' | jq -r '.val |=@base64d'

产量:

{ "val": "30\n\n" }

旁注jq只是jq-win64.exe

的一个符号文件