【问题标题】:filter specific entries in an array using jq使用 jq 过滤数组中的特定条目
【发布时间】:2019-12-15 08:47:17
【问题描述】:

我会尽量简短。 这就是我要处理的。我有一个使用 curl 的链接来管道 json 格式输出以使用 jq 过滤特定条目。 这是json文件

{
    "remote":  [
        {"name": "cast-1",
         "id": 1212
        },
        {"name": "cast-1",
         "id": 1214
        },
        {"name": "home-11",
         "id": 3212
        },
        {"name": "cast-3",
         "id": 3212
        },
        {"name": "cast-3",
         "id": 3213
        },
        {"name": "cast-4",
         "id": 4211
        }

    ]
}

我想要的输出是

 "cast-1": 1212 , 1214,
 "cast-3": 3212 , 3213,
 "cast-4": 4211,

通过我的尝试,我只能输出这个

 "cast-1": 1214,
 "cast-3": 3213, 
 "cast-4": 4211,

到目前为止我的代码

curl ... | jq  'reduce .remote[] as $v ({}; . + {"\($v.name)":$v.id})'  

无法从 cast-1 和 cast-3 中添加第二个 id。 有没有一种方法来格式化输出,以获得有效的 JSON 输出格式? 也许是 python 或 perl 方法?我对 awk 不熟悉,sed 让你知道。

【问题讨论】:

  • 您想要的输出不是有效的 JSON 值

标签: arrays json bash curl jq


【解决方案1】:

这里不需要 reduce,group_by 就足够了。例如:

.remote | group_by(.name) | map({(.[0].name): map(.id)}) | add

https://jqplay.org/s/_0CFADWu2G

【讨论】:

  • @mogul05 我不明白你在说什么。您在使用此脚本调用 jq 时遇到问题吗?
  • 我的错,我刚刚修好了。忘记设置单引号了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-17
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多