【问题标题】:group by and create a transformed json output分组并创建转换后的 json 输出
【发布时间】:2018-11-27 16:27:18
【问题描述】:

我的数据如下所示 我需要改造它们。

[{"us":{"$event":"5bbf4a4f43d8950b5b0cc6d2"},"org":"TΙ UIH","rc":{"$event":"13"}},
{"us":{"$event":"5bbf4a4f43d8950b5b0cc6d3"},"org":"TΙ UIH","rc":{"$event":"13"}},
{"us":{"$event":"5bbf4a4f43d8950b5b0cc6d4"},"org":"AB KIO","rc":{"$event":"13"}},
{"us":{"$event":"5bbf4a4f43d8950b5b0cc6d5"},"org":"GH SVS","rc":{"$event":"17"}}]

我用什么:

`[group_by(.org, .rc."$event")[] | [.[0].rc."$event", .[0].org, length]] |` sort_by(.[0])[] 

我得到的输出:

[
  "13",
  "AB KIO",
  1
]
[
  "17",
  "GH SVS",
  1
]
[
  "13",
  "TΙ UIH",
  2
]

我怎样才能得到以下格式作为输出?

key1: ["",""]
key2: ["",""]

其中每个键是事件的编号,在数组中,我们有每个事件组织的唯一值。

输出 13:[“AB KIO”,“TΙ UIH”] 17:[“GH SVS”]

【问题讨论】:

  • 您知道您显示的输入和输出是无效的 JSON 吗?请修复和/或澄清您的意图。谢谢。

标签: json group-by jq


【解决方案1】:
def aggregate_by(f; g):
  reduce .[] as $x  ({}; .[$x|f] += [$x|g]);

map( {rc: (.rc|.["$event"]), org} )
| aggregate_by(.rc; .org)
| map_values(unique)

将您的示例输入修改为 JSON 数组,上面的 jq 程序会生成:

{"13":["AB KIO","TΙ UIH"],"17":["GH SVS"]}

当然有很多变化是可能的,但是对于推迟唯一化有一些话要说。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多