我有一个JSON文件如下:
[{
"macAddress": "ac:5f:3e:87:d7:1a",
"ip": "1.2.3.4"
},
{
"macAddress": "ac:5f:3e:87:d7:2a",
"ip": "1.2.3.4"
},
{
"macAddress": "ac:5f:3e:87:d7:3a",
"ip": "1.2.3.4"
}]
使用jq
哈希macAddress
字段,如下所示:
jq .[] | hash(.macAddress)
我可以定义自己的哈希函数并让jq
在解析过程中运行哈希吗?
我的预期哈希函数可以像使用本机linux命令md5sum
echo -n "my_salt""42:12:20:2e:2b:ca" | md5sum
d973ea7c353e78ba1724efbc8054dfdc -
所以输出json将是
[{
"macAddress": "d973ea7c353e78ba1724efbc8054dfdc",
"ip": "1.2.3.4"
},
{
"macAddress": "d973ea7c353e78ba1724efbc8054d2er",
"ip": "1.2.3.4"
},
{
"macAddress": "d973ea7c353e78ba2324efbc8054d123",
"ip": "1.2.3.4"
}]
答案 0 :(得分:1)
我的预期哈希函数可以很简单,因为使用原生linux命令 md5sum
这是原生的,可能是合适的;
jq -c .[] "$jsonfile" |
while read -r jsonline ; do
hashmac="$(jq --arg mysalt "$mysalt" -s -j '
.[] | "\($mysalt)" + .macAddress' <<<"$jsonline" |
md5sum | cut -d ' ' -f1)"
jq --arg hashmac "$hashmac" -s -r '
.[] | .macAddress |= "\($hashmac)"' <<<"$jsonline"
done
[{
"macAddress": "ac:5f:3e:87:d7:1a",
"ip": "1.2.3.4"
},
{
"macAddress": "ac:5f:3e:87:d7:2a",
"ip": "1.2.3.4"
},
{
"macAddress": "ac:5f:3e:87:d7:3a",
"ip": "1.2.3.4"
},
{
"macAddress": "42:12:20:2e:2b:ca",
"ip": "1.2.3.4"
}]
{
"macAddress": "1f960fe4d24684ca44e5e67b6259362c",
"ip": "1.2.3.4"
}
{
"macAddress": "3527422754ecbfdd01d48b17fce87842",
"ip": "1.2.3.4"
}
{
"macAddress": "9bc8da72324448c3032a20fb67a31466",
"ip": "1.2.3.4"
}
{
"macAddress": "d973ea7c353e78ba1724efbc8054dfdc",
"ip": "1.2.3.4"
}
-j
导致jq无法输出换行符,相当于您的echo -n
示例
此示例中的变量使用jq
作为字符串发送到-arg
,并引用为"\($var)"
,而不是直接转义变量,例如:
"\($mysalt)" + .macAddress'
(jq变量)
而不是:
"'"$mysalt"'" + .macAddress'
(直接替换贝壳)
此示例使用cut -d ' ' -f1
修剪-
,但可能有更好的方法
jq --arg hashmac "$hashmac" -s -r '.[] |= . + {"hashAddress":"\($hashmac)"}'
会附加json
[
{
"macAddress": "ac:5f:3e:87:d7:1a",
"ip": "1.2.3.4",
"hashAddress": "1f960fe4d24684ca44e5e67b6259362c"
}
]
等
答案 1 :(得分:0)
接受的答案需要2n + 1个jq调用,其中n是消息摘要函数的调用次数。
要将调用次数减少到2次,请参阅shell-out value to md5 (crypto) function