JQ~有没有更好的方法来折叠单对象数组? [英] jq ~ is there a better way to collapse single object arrays?

查看:11
本文介绍了JQ~有没有更好的方法来折叠单对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题: 这是执行此操作的最佳方法吗?

工具:

jq --version jq-1.5-1-a5b5cbe

要求:递归标识仅包含单个对象的数组{},并将该数组转换回标准对象{}。实质上是在不需要的时候剥离父数组。

看起来有效的方法:

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

使用案例: Google Custom Search JSON包含大量数组,其中许多是单对象数组。Logstashinputcodec => json和/或json筛选器似乎无法自动将单个对象数组转换为ElasticSearch字段。

推荐答案

最简单的方法是使用walk/1,但它是在JQ1.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)

这篇关于JQ~有没有更好的方法来折叠单对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆