jq 加入公钥

jq join on common key

我是 jq 的新手,这个 post 是因为不了解 jq 背后的机制。 我可以开发一个 bash 脚本,它可以做我想做的事,但 jq 和它的 JSON 超能力引起了我的兴趣,我想通过应用于现实世界场景来学习它。这是一个...

顺便说一句,我尝试使用现有的 jq 相关 SO 解决方案 merging/joining JSONs 但失败了。

最接近我需要的是使用 INDEX 和 $x + 的串联。 , 但是我只从我的第二个 (c2) json.

得到最后一个项目

所以,我的问题如下:

有两个 JSON 个文件:

我的输出要求是: 我想获得一个(每行一个或单个数组)列表,其中包含 c1 和 c2 数组之间匹配 key/values 对的所有组合,其中“类型”键(字符串)的值在 c1 和c2 正好。

还有一个问题,将解决方案扩展到同时在三个 JSON 文件之间执行类似的 matching/joining 会困难多少 - 再次在特定键的相同值上?

任何关于如何解决和理解如何解决这个问题的帮助甚至只是提示都将不胜感激!

第一个输入文件:JSON#1,数组 c1(集合 1)

{ "c1":
[
{ "c1id":1, "type":"alpha" },
{ "c1id":2, "type":"beta" }
]
}

第二个输入文件:JSON#2,数组 c2(集合 2)

{
"c2":
[
{ "c2id":1,"type":"alpha","serial":"DDBB001"} ,
{ "c2id":2,"type":"beta","serial":"DDBB007"} ,
{ "c2id":3,"type":"alpha","serial":"DDTT005"} ,
{ "c2id":4,"type":"beta","serial":"DDAA002"} ,
{ "c2id":5,"type":"yotta","serial":"DDCC017"}
]
}

预期输出:

{"c1id":1,"type":"alpha","c2id":1,"serial":"DDBB001"}
{"c1id":1,"type":"alpha","c2id":3,"serial":"DDTT005"}
{"c1id":2,"type":"beta","c2id":2,"serial":"DDBB007"}
{"c1id":2,"type":"beta","c2id":4,"serial":"DDAA002"} 

您会注意到 c2 中的类型“yotta”未包含在输出中。这是意料之中的。只有存在于 c1 中且与 c2 匹配的“类型”才会出现在结果中。我想这暗示这是一个 matching/joining 练习 - 我添加它只是为了清楚 - 我希望它有效。

下面是一个使用 INDEX 和 JOIN 的例子:

jq --compact-output --slurpfile c1 c1.json '
    INDEX(
        $c1[0].c1[];
        .type
    ) as $index |
    JOIN(
        $index;
        .c2[];
        .type;
        reverse|add
    )
' c2.json

INDEX 的第一个参数需要生成项目流,这就是为什么我们应用 [] 从数组中单独获取项目的原因。第二个参数选择我们的索引键。

我们使用 JOIN 的四参数版本。第一个参数是索引本身,第二个是要连接到索引的对象流,第三个参数从流对象中选择查找键,第四个参数是 assemble 连接对象的表达式.该表达式的输入是两项数组的流,每个数组看起来像这样:

[{"c2id":1,"type":"alpha","serial":"DDBB001"},{"c1id":1,"type":"alpha"}]

因为我们只想组合我们刚刚使用的对象的所有键和值 add,但我们首先 reverse 数组以在 c2 字段之前很好地排列 c1 字段。最终结果如你所愿:

{"c1id":1,"type":"alpha","c2id":1,"serial":"DDBB001"}
{"c1id":2,"type":"beta","c2id":2,"serial":"DDBB007"}
{"c1id":1,"type":"alpha","c2id":3,"serial":"DDTT005"}
{"c1id":2,"type":"beta","c2id":4,"serial":"DDAA002"}