我实际上是在寻找一种基于几个"索引"合并几个(3-4)数组的解决方案。键。
示例阵列1:
{"Fan":[{ "Last Name":Mueller,"Firstname":Martin,"Adress":Madisson Square,"City":"New York","DegreesIndex":3,"SchoolIndex2":1,}]
DegreesIndex和Schoolindex引用另外两个阵列中的两个不同的键:
示例数组2:
{"Degrees":[
{"DegreesIndex":3,
"Key":"12759303,
"Degrees":1.6}]}
示例数组3:
{"学校":[ {" SchoolIndex":1, "预告":" 12759303.8, "师":米勒}]}
如何基于"索引"合并该数组?在Windows10下使用JQ 1.5的键?
此致 蒂莫
答案 0 :(得分:1)
我相信这可能接近你正在寻找的东西:
# input: an object
def merge_by_index(obj; ix):
ix as $index
| . + (obj | map( select( ix == $index)) [0] )
| del(ix) ;
清理完样本输入后,假定a1,a2和a3为 三个顶级对象:
a1
| .Fan[0] |= merge_by_index(a2|.Degrees; .DegreesIndex)
| .Fan[0] |= merge_by_index(a3|.School; .SchoolIndex)
产生
{
"Fan": [
{
"Last Name": "Mueller",
"Firstname": "Martin",
"Adress": "Madisson Square",
"City": "New York",
"Key": 12759303,
"Degrees": 1.6,
"Teaser": 12759303.8,
"Trainer": "Miller"
}
]
}
答案 1 :(得分:0)
以下是我将如何处理这个问题。这比peak的方法更加冗长。
首先用数据定义一些数组。请注意,我冒昧地添加了另一个条目,用于测试当给定粉丝的 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"
}
}
如果您需要不同的嵌套或输出,这应该很容易调整。