sol*_*ify 6 bash parsing json jq
我想通过利用jq为JSON格式的数据片段中的每个字段运行bash命令.
{
"apps": {
"firefox": "1.0.0",
"ie": "1.0.1",
"chrome": "2.0.0"
}
}
Run Code Online (Sandbox Code Playgroud)
基本上我想要这样的东西:
foreach app:
echo "$key $val"
done
Run Code Online (Sandbox Code Playgroud)
假设您想列出apps对象的键/值:
$ jq -r '.apps | to_entries[] | "\(.key)\t\(.value)"' input.json
Run Code Online (Sandbox Code Playgroud)
要使用输出作为参数调用另一个程序,您应该熟悉xargs:
$ jq -r '...' input.json | xargs some_program
Run Code Online (Sandbox Code Playgroud)
这是一个 bash 脚本,演示了可能的解决方案。
#!/bin/bash
json='
{
"apps": {
"firefox": "1.0.0",
"ie": "1.0.1",
"chrome": "2.0.0"
}
}'
jq -M -r '
.apps | keys[] as $k | $k, .[$k]
' <<< "$json" | \
while read -r key; read -r val; do
echo "$key $val"
done
Run Code Online (Sandbox Code Playgroud)
输出示例
chrome 2.0.0
firefox 1.0.0
ie 1.0.1
Run Code Online (Sandbox Code Playgroud)