【问题标题】:convert column arrays to array of row objects将列数组转换为行对象数组
【发布时间】:2020-08-30 15:58:28
【问题描述】:

我有一个 json 文件,代表一个有两列的表。

列值在一个数组中

{ 'columnA':[1,2,3], 'columnB':[6,7,8] }

我需要将其转换为行数组:

[ {'columnA':1, 'columnB':6}, {'columnA':2, 'columnB':7}, {'columnA':3, 'columnB':8}, ]

【问题讨论】:

  • 您为自己尝试了什么?纯 JSON 不为关键字段使用单引号
  • transpose 导致错误:Cannot index object with number force string keys with to_entries or even map(to_entries) did not lead to any usefull but map will only ittererate one column and not result以任意键访问第二列

标签: arrays json object jq transpose


【解决方案1】:

这是一种解决方案:

[range(0; .columnA|length) as $i
 | {columnA: .columnA[$i], columnB: .columnB[$i]}]

这是另一个与键名无关的,应该适用于任意数量的“列”:

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))

【讨论】:

  • 谢谢。有许多答案会导致相同的结果。接受这个,因为它是第一个。
【解决方案2】:

使用transpose 内置:

[ [{columnA: .columnA[]}],
  [{columnB: .columnB[]}]
] | transpose | map(add)

【讨论】:

  • 谢谢。有许多答案会导致相同的结果。我接受了第一个,虽然我喜欢这种方法!
【解决方案3】:

我想通了:

[.columnA,.columnB] | transpose | map({"columnA":.[0], "columnB": .[1]})

  1. 转换为数组数组
  2. 转置
  3. 转换回对象

【讨论】:

    猜你喜欢
    • 2021-05-03
    • 2018-12-04
    • 2021-06-16
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    相关资源
    最近更新 更多