将列数组转换为行对象数组
convert column arrays to array of row objects
我有一个 json 文件代表一个 table 有两列。
列值在数组中
{
'columnA':[1,2,3],
'columnB':[6,7,8]
}
我需要将其转换为行数组:
[
{'columnA':1, 'columnB':6},
{'columnA':2, 'columnB':7},
{'columnA':3, 'columnB':8},
]
这是一种解决方案:
[range(0; .columnA|length) as $i
| {columnA: .columnA[$i], columnB: .columnB[$i]}]
这是另一个键名中立的,应该适用于任意数量的 "columns":
def objectify($template):
. as $in
| ($template|keys_unsorted) as $k
| reduce range(0; $k|length) as $i (null; . + {($k[$i]): $in[$i]});
. as $in
| [.[]]
| transpose
| map(objectify($in))
使用 transpose
内置函数:
[ [{columnA: .columnA[]}],
[{columnB: .columnB[]}]
] | transpose | map(add)
我想通了:
[.columnA,.columnB] | transpose | map({"columnA":.[0], "columnB": .[1]})
- 转换为数组的数组
- 转置
- 转换回对象
我有一个 json 文件代表一个 table 有两列。
列值在数组中
{
'columnA':[1,2,3],
'columnB':[6,7,8]
}
我需要将其转换为行数组:
[
{'columnA':1, 'columnB':6},
{'columnA':2, 'columnB':7},
{'columnA':3, 'columnB':8},
]
这是一种解决方案:
[range(0; .columnA|length) as $i
| {columnA: .columnA[$i], columnB: .columnB[$i]}]
这是另一个键名中立的,应该适用于任意数量的 "columns":
def objectify($template):
. as $in
| ($template|keys_unsorted) as $k
| reduce range(0; $k|length) as $i (null; . + {($k[$i]): $in[$i]});
. as $in
| [.[]]
| transpose
| map(objectify($in))
使用 transpose
内置函数:
[ [{columnA: .columnA[]}],
[{columnB: .columnB[]}]
] | transpose | map(add)
我想通了:
[.columnA,.columnB] | transpose | map({"columnA":.[0], "columnB": .[1]})
- 转换为数组的数组
- 转置
- 转换回对象