我有这个文件:
[
"smoke-tests",
"push-apps-manager"
]
我想使用JQ获得此输出:
{
"errands": [
{"name": "smoke-tests", "post_deploy": true},
{"name": "push-apps-manager", "post_deploy": true}
]
}
看起来很简单,但我在这里遇到了很多困难......
答案 0 :(得分:2)
这有点棘手,因为您需要将输入嵌入绑定到errands
键的列表中。首先创建name
/ post_deploy
个对象的序列:
% jq '.[] | {name: ., post_deploy: true}' names.json
{
"name": "smoke-tests",
"post_deploy": true
}
{
"name": "push-apps-manager",
"post_deploy": true
}
然后将其包装在外部对象的列表中:
% jq '{errands: [.[] | {name: ., post_deploy: true}]}' names.json
{
"errands": [
{
"name": "smoke-tests",
"post_deploy": true
},
{
"name": "push-apps-manager",
"post_deploy": true
}
]
}
你也可以使用map
函数(我很少记得如何正确使用,但事实证明这很简单):
% jq '{errands: map({name:., post_deploy: true})}' names.json
答案 1 :(得分:1)
这是另一种方法。如果您是 jq 的新手,最简单的方法就是以最小的步骤实现目标。
1)从身份过滤器
开始 .
按预期产生
[
"smoke-tests",
"push-apps-manager"
]
2)接下来使用"errands"
键添加外部对象:
{ "errands": . }
产生
{
"errands": [
"smoke-tests",
"push-apps-manager"
]
}
3)接下来将数据移动到数组
{ "errands": [ . ] }
产生
{
"errands": [
[
"smoke-tests",
"push-apps-manager"
]
]
}
4)使用"name"
和"post_deploy"
键
{ "errands": [ { "name": ., "post_deploy": true } ] }
产生
{
"errands": [
{
"name": [
"smoke-tests",
"push-apps-manager"
],
"post_deploy": true
}
]
}
5)现在我们真的很接近。我们需要做的就是利用 jq ' Object Construction behavior when an expression produces multiple results:
{ "errands": [ { "name": .[], "post_deploy": true } ] }
给了我们想要的结果
{
"errands": [
{
"name": "smoke-tests",
"post_deploy": true
},
{
"name": "push-apps-manager",
"post_deploy": true
}
]
}