通过 jq 为每个 JSON 项运行 bash 命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38779732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Running bash commands for each JSON item through jq
提问by solemnify
I would like to run a bash command for each field in a JSON formatted piece of data by leveraging jq.
我想通过利用 jq 为 JSON 格式的数据段中的每个字段运行一个 bash 命令。
{
"apps": {
"firefox": "1.0.0",
"ie": "1.0.1",
"chrome": "2.0.0"
}
}
Basically I want something of the sort:
基本上我想要这样的东西:
foreach app:
echo "$key $val"
done
采纳答案by Jeff Mercado
Assuming you wanted to list out the key/values of the apps
object:
假设您想列出apps
对象的键/值:
$ jq -r '.apps | to_entries[] | "\(.key)\t\(.value)"' input.json
To invoke another program using the output as arguments, you should get acquainted with xargs:
要使用输出作为参数调用另一个程序,您应该熟悉xargs:
$ jq -r '...' input.json | xargs some_program
回答by jq170727
Here is an bash script which demonstrates a possible solution.
这是一个 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
Example output
示例输出
chrome 2.0.0
firefox 1.0.0
ie 1.0.1