如何使用jq在特定字段上联接JSON对象? [英] How to join JSON objects on particular fields using jq?
问题描述
我具有以下JSON结构:
I have following JSON structure:
{
"Reservations": [
{
"Id": "R-1",
"CustomerId": "1"
},
{
"Id": "R-2",
"CustomerId": "2"
}
],
"Customers": [
{
"Id": "1",
"Name": "customer 1"
},
{
"Id": "2",
"Name": "customer 2"
},
{
"Id": "3",
"Name": "customer 3"
}
]
}
我想与 Customers
一起加入 Reservations
,并获得如下信息:
I want to join Reservations
with Customers
and get something like this:
{
"ReservationId": "R-1",
"CustomerName": "customer 1"
}
{
"ReservationId": "R-2",
"CustomerName": "customer 2"
}
我已经广泛地使用过 jq
,尝试使用多个用逗号分隔的过滤器,尝试使用变量,阅读文档,但是使用 jq似乎无法完成如此简单的任务
.或者,我想念什么吗?
I've played with jq
extensively, tried using multiple filters separated by comma, tried using variables, read the docs, but it seems like doing such a simple tasks is impossible with jq
. Or, am I missing something?
推荐答案
这是使用 INDEX/2
的简单解决方案:
Here's a simple solution using INDEX/2
:
INDEX(.Customers[]; .Id) as $c
| .Reservations[]
| { ReservationId: .Id,
CustomerName: $c[.CustomerId].Name }
如果您的jq没有 INDEX/2
,那么现在是升级的好时机;否则,您可以从 https://复制并粘贴其定义github.com/stedolan/jq/blob/master/src/builtin.jq ,或者您可以使用如下定义的 INDEX/3
.
If your jq does not have INDEX/2
then now would be a good time to upgrade; otherwise, you can copy-and-paste its def from https://github.com/stedolan/jq/blob/master/src/builtin.jq, or you could use INDEX/3
as defined below.
def INDEX(s; k; v):
reduce s as $x ({}; .[$x|k] = ($x|v));
INDEX(.Customers[]; .Id; .Name) as $c
| .Reservations[]
| { ReservationId: .Id,
CustomerName: $c[.CustomerId] }
这篇关于如何使用jq在特定字段上联接JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!