下面是我将如何处理这个问题。这是更详细一点,然后peak的方法。
首先用数据定义一些数组。请注意,我冒昧添加另一个条目来测试当没有匹配的DegreesIndex或SchoolIndex对于给定的Fan。我喜欢在这里使用函数,因为您可以轻松地用您需要的任何逻辑来替换这些函数以获取真实数据。
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。
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"
}
}
这应该如果您需要不同的嵌套或输出,很容易调整。
1.请修复JSON。 2.请在http://stackoverflow.com/help/mcve上查看指导原则后澄清问题 – peak