【问题标题】:jq ~ is there a better way to collapse single object arrays?jq ~ 有没有更好的方法来折叠单个对象数组?
【发布时间】:2018-12-11 22:38:33
【问题描述】:

问题: 这是最好的方法吗?

工具:

jq --version jq-1.5-1-a5b5cbe

要求:递归识别仅包含单个对象{} 的数组[] 并将数组转换回标准对象{}。本质上是在不需要时去除父数组。

什么似乎有效:

(..|select(type=="array" and .[1] == null ) | . ) |= add | .

用例: Google 自定义搜索 JSON 包含大量数组,其中许多是单对象数组。 Logstash inputcodec => json 和/或 json 过滤器似乎无法自动将单个对象数组转换为弹性搜索字段。

【问题讨论】:

  • 要测试数组的长度是否为 1,您不能依赖测试 .[1]==null,因为第二个元素可能为空。您的“似乎正在运行”程序还有其他问题。

标签: json jq


【解决方案1】:

最简单的方法是使用walk/1,不过它是在 jq 1.5 发布之后才引入的。因此,以下包括其定义:

# Apply f to composite entities recursively, and to atoms
def walk(f): 
  . as $in
  | if type == "object" then
      reduce keys[] as $key
        ( {}; . + { ($key):  ($in[$key] | walk(f)) } ) | f
  elif type == "array" then map( walk(f) ) | f
  else f
  end;

walk(if type=="array" and length==1 and (.[0]|type) == "object" then .[0] else . end)

当然,许多变体都是可能的,例如按照你的程序:

walk(if type=="array" and length==1 then .[0] else . end)

【讨论】:

    猜你喜欢
    • 2021-12-31
    • 2013-11-09
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    相关资源
    最近更新 更多