通过 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:59:14  来源:igfitidea点击:

Running bash commands for each JSON item through jq

jsonbashparsingjq

提问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 appsobject:

假设您想列出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