通过jq为每个JSON项运行bash命令

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)

Jef*_*ado 6

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

  • 考虑到 json 中的引用/括号问题,除非 some_program 只接受 1 个参数,否则这不太可能按预期工作。 (2认同)

jq1*_*727 5

这是一个 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)