使用jq递归化简数组 [英] recursive reduce arrays using jq

查看:51
本文介绍了使用jq递归化简数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何递归地找到对象中的所有数组并将它们简化为第一项?

How can I recursive find all arrays in object and reduce them to first item ?

我尝试使用if .[0]? == "" then .[0] else . end检测数组,但是如果当前对象不是数组,它不会输出任何内容.

I tried to detect array using if .[0]? == "" then .[0] else . end but it not output anything if current object is not array.

输入:

{
  "a": 1,
  "b": [
    1,
    2,
    3
  ],
  "c": [
    {
      "a": 1,
      "b": [
        1,
        2,
        3
      ],
      "c": {
        "a": 1,
        "b": [
          1,
          2,
          3
        ]
      }
    },
    {
      "a": 1,
      "b": [
        1,
        2,
        3
      ],
      "c": {
        "a": 1,
        "b": [
          1,
          2,
          3
        ]
      }
    },
    {
      "a": 1,
      "b": [
        1,
        2,
        3
      ],
      "c": {
        "a": 1,
        "b": [
          1,
          2,
          3
        ]
      }
    }
  ]
}

输出:

{
  "a": 1,
  "b": [
    1
  ],
  "c": [
    {
      "a": 1,
      "b": [
        1
      ],
      "c": {
        "a": 1,
        "b": [
          1
        ]
      }
    }
  ]
}

推荐答案

walk/1包含在jq的最新版本(1.5版之后)中.也可以在下面找到.

walk/1 is included in recent (post-1.5) releases of jq. It is also available below.

据我了解,这是可以用来实现您的目标的方式:

Here's how it can be used to achieve your objective as I understand it:

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


# 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;

这篇关于使用jq递归化简数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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