问题描述
我有两个JSON文件,如下所示.
I have two JSON files as follows.
一个包含项目到所有者的映射.
One contains a mapping of project to owners.
owners.json
{
"Project1": "owner1",
"Project2": "owner2"
}
第二个包含具有更多信息的项目列表:
The second contains a list of projects with extra information:
projects.json
[
{
"name": "Project1",
"base": "A"
},
{
"name": "Project2",
"base": "B"
}
]
我想使用JQ合并两个文件,如下所示:
I'd like to use JQ to merge the two files to look like the following:
output.json
[
{
"name": "Project1",
"owner": "owner1",
"base": "A"
},
{
"name": "Project2",
"owner": "owner2",
"base": "B"
}
]
我的第一个念头是尝试这样的事情(假设projects.json
是在stdin上输入的):
My first thought was to try something like this (assuming projects.json
is fed on stdin):
jq --slurpFile owners owners.json '.name as $n | [.[] | {name, base, owner: $owners[0].$n}]'
这给出了与$owners[0].$n
中的$n
有关的语法错误.在JQ中执行此操作的正确方法是什么?
This gives a syntax error relating to the $n
in $owners[0].$n
. What's the right way to do this in JQ?
谢谢!
推荐答案
您需要将变量引用包装在方括号中,以便使用它们为对象建立索引.即使您已纠正脚本无法正常工作,因为数组无法使用字符串索引(.name as $n
部分).
You need to wrap variable references in square brackets for indexing objects with them. Even though you corrected that your script wouldn't work as arrays can't be indexed with strings (.name as $n
part).
不要打扰slurpfile,有更简单的方法.
And don't bother with slurpfile, there are simpler ways.
$ jq 'input as $owners | map(.owner = $owners[.name])' projects.json owners.json
[
{
"name": "Project1",
"base": "A",
"owner": "owner1"
},
{
"name": "Project2",
"base": "B",
"owner": "owner2"
}
]
这篇关于如何在jq中使用值作为键引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!