【发布时间】:2021-10-13 12:33:53
【问题描述】:
所以从我收集到的jq does support 使用-f 多次。但是我不确定这是否是我想要的。
所以我有:
cats.json
{
"cats": [
{
"name": "fluffles",
"age": 10,
"color": "white"
}
]
}
dogs.json
{
"dogs": [
{
"name": "sam",
"age": 5,
"color": "black and white"
},
{
"name": "rover",
"age": 2,
"color": "brown and white"
}
]
}
snakes.json
{
"snakes": [
{
"name": "noodles",
"age": 10,
"color": "green"
}
]
}
我能够合并这个对象:
owners.json
{
"owners": [
"peter",
"william",
"sally"
]
}
使用
jq -n -f program.jq owners.json $(ls *.json | grep -v 'owners.json')
其中包含jq 程序
input as $owners | {$owners, animals: [inputs]}
按照in the reply的建议。
但是,如果我想合并两个额外的对象,我不确定该怎么做,比如说我有:
food.json
{
"food": [
"meat",
"fish",
"vegetables"
]
}
以及我想要在顶部,导致:
{
"owners": [
"peter",
"william",
"sally"
],
"food": [
"meat",
"fish",
"vegetables"
],
"animals": [
{
"cats": [
{
"name": "fluffles",
"age": 10,
"color": "white"
}
]
},
{
"dogs": [
{
"name": "sam",
"age": 5,
"color": "black and white"
},
{
"name": "rover",
"age": 2,
"color": "brown and white"
}
]
},
{
"snakes": [
{
"name": "noodles",
"age": 10,
"color": "green"
}
]
}
]
}
【问题讨论】:
-
ls | grep的用途是什么?它是generally an antipattern,我很难看到这里的值(如果你想在命令行上扩展*owners.json*以列出具有它作为子字符串的文件,你可以在没有ls的情况下这样做)。 -
jq 和 gojq 都不支持多个
-f FILE选项,除非第一个这样的规范被忽略。您误读了您引用的(已关闭)“问题”。由于多次使用 -f 选项确实与问题无关,为避免混淆,我建议您只需删除 Q 的第一段。 -
@CharlesDuffy - 你建议
ls *.jq | grep -v '^owners\.json$的替代品是什么? (注意 -v 选项。) -
@peak,启用 extglob,
!(*owners.json*).jq。但是*.jq怎么可能一开始就匹配owners.json呢? -
我通过将 slurped 文件移动到与其他 .json 文件不同的位置来简化它,这意味着我不再需要 grep 选项,并且它们不会被读取两次。例如:
jq -n -f program.jq --slurpfile owners /slurp/owners.json --slurpfile food /slurp/food.json /animals/*.json带有 jqprogram:{$owners, food: $food[0].food, animals: [inputs]}
标签: json shell command-line jq