【问题标题】:reformat json with jq - collect results in array使用 jq 重新格式化 json - 将结果收集到数组中
【发布时间】:2020-07-31 21:48:31
【问题描述】:

我有一个返回 json 的查询,如下所示:

{
  "hostname": "seapr1pgdb032",
  "ip": "10.215.0.6",
  "dataCenter": "seapr1"
}
{
  "hostname": "seapr1cpndb001",
  "ip": "10.203.0.41",
  "dataCenter": "seapr1"
}
{
  "hostname": "seapr1dhcp01",
  "ip": "10.205.3.212",
  "dataCenter": "seapr1"
}

数据中心可以变化,我想将每个数据中心的所有主机收集到一个对象中,如下所示:

{
 "dataCenter": "seapr1",
 "hosts": [
    "seapr1pgdb032",
    "seapr1cpndb001",
    "seapr1dhcp01"
  ] 
}

Reshaping JSON with jq 工作,我认为这样做可以:

{dataCenter: .dataCenter, hosts: [.hostname] } 

但我得到了三个数据中心对象,而不是我预期的单个合并对象:

{
  "dataCenter": "seapr1",
  "hosts": [
    "seapr1pgdb032"
  ]
}
{
  "dataCenter": "seapr1",
  "hosts": [
    "seapr1cpndb001"
  ]
}
{
  "dataCenter": "seapr1",
  "hosts": [
    "seapr1dhcp01"
  ]
}

【问题讨论】:

  • 简单。从jq -s 'groub_by(.dataCenter)'开始,你可以自己做。
  • 谢谢 - 我想我也可以使用它。

标签: json group-by jq


【解决方案1】:

这是一个 jq 解决方案,它避免了内置的 group_by 过滤器,原因在下面的 cmets 中解释。

# This stream-oriented variant of the built-in `group_by` emits a stream of arrays,
# each array representing a group. The main advantages over `group_by` are
# that no sorting is required, and the ordering of items within a group is preserved.
# There are no restrictions on f or the items in the stream;
# in particular, f may evaluate to any number of values,
# but if f evaluates to empty at any item in the stream, then that item will in effect be discarded.
# Example:
#  GROUPS_BY( 4,3,2,1; . % 2 ) => [4,2] [3,1]

def GROUPS_BY(stream; f): 
  reduce stream as $x ({};
    reduce [$x|f][] as $s (.;
        ($s|type) as $t
        | (if $t == "string" then $s
           else ($s|tojson) end) as $y
        | .[$t][$y] += [$x] ) ) 
  | .[][] ;

使用 -n 命令行选项,我们可以通过编写如下解决方案来避免“吞咽”输入:

GROUPS_BY(inputs; .dataCenter)
| {dataCenter: .[0].dataCenter, hosts: map(.hostname) }

【讨论】:

  • @joseph - 请根据minimal reproducible example 指南提出一个新的 SO 问题。
  • 感谢您抽出宝贵时间回答我,如果您愿意帮助codeproject.com/Questions/5275389/…,您将在这里找到所有内容
  • 在那里回答。如果您也遵循minimal reproducible example ton codeproject.com 指南,这可能是一个好主意,即显示您实际想要的输出以及您使用 jq 的尝试。
  • omg 谢谢你的好意,问题是我花了 2 天的时间在这上面,我越来越绝望,可以说 jq 官方文档可能会更好。谢谢楼主
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-26
  • 2022-07-07
相关资源
最近更新 更多