以下是我的处理方法。这比peak 的方法要冗长一些。
首先用数据定义一些数组。请注意,我冒昧地添加了另一个条目来测试当给定 Fan 没有匹配的 DegreesIndex 或 SchoolIndex 时会发生什么。我喜欢在这里使用函数,因为您可以轻松地将它们替换为获取真实数据所需的任何逻辑。
def array1: {
"Fan": [
{
"Last Name":"Mueller", "First Name":"Martin",
"Address": "Madisson Square", "City": "New York",
"DegreesIndex": 3, "SchoolIndex": 1
},
{
"Last Name":"Roberts", "First Name":"Bob",
"DegreesIndex": 2, "SchoolIndex": 4
},
{
"Last Name":"Skywalker", "First Name":"Luke",
"DegreesIndex": 5, "SchoolIndex": 1
}
]};
def array2: {
"Degrees": [
{ "DegreesIndex":3, "Key": "12759303", "Degrees":1.6 },
{ "DegreesIndex":2, "Key": "2", "Degrees":2 }
]};
def array3: {
"School": [
{ "SchoolIndex":1, "Teaser":"12759303.8", "Trainer":"Miller" },
{ "SchoolIndex":2, "Teaser":"2", "Trainer":"Miller" }
]};
现在定义一些简单的查找函数,它们将返回与指定键匹配的记录。请注意,如果未找到该项目,则使用 [ ... ][0] 构造返回 null,而不是导致完全省略 Fan。
def LookupDegrees($i):
[
array2
| .Degrees[]
| select(.DegreesIndex == $i)
][0]
;
def LookupSchool($i):
[
array3
| .School[]
| select(.SchoolIndex == $i)
][0]
;
所有这些都使主程序变得简单:
array1
| .Fan[]
| .Degrees = LookupDegrees(.DegreesIndex)
| .School = LookupSchool(.SchoolIndex)
这是我使用 jq -n -f file.jq 运行时得到的结果
{
"Last Name": "Mueller",
"First Name": "Martin",
"Address": "Madisson Square",
"City": "New York",
"DegreesIndex": 3,
"SchoolIndex": 1,
"Degrees": {
"DegreesIndex": 3,
"Key": "12759303",
"Degrees": 1.6
},
"School": {
"SchoolIndex": 1,
"Teaser": "12759303.8",
"Trainer": "Miller"
}
}
{
"Last Name": "Roberts",
"First Name": "Bob",
"DegreesIndex": 2,
"SchoolIndex": 4,
"Degrees": {
"DegreesIndex": 2,
"Key": "2",
"Degrees": 2
},
"School": null
}
{
"Last Name": "Skywalker",
"First Name": "Luke",
"DegreesIndex": 5,
"SchoolIndex": 1,
"Degrees": null,
"School": {
"SchoolIndex": 1,
"Teaser": "12759303.8",
"Trainer": "Miller"
}
}
如果您需要不同的嵌套或输出,这应该很容易调整。