如何使用jq查找到某个键​​的所有路径 [英] How to use jq to find all paths to a certain key

查看:112
本文介绍了如何使用jq查找到某个键​​的所有路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个非常大的嵌套json结构中,我试图找到所有以键结尾的路径.

In a very large nested json structure I'm trying to find all of the paths that end in a key.

例如:

{
  "A": {
    "A1": {
      "foo": {
        "_": "_"
      }
    },
    "A2": {
      "_": "_"
    }
  },
  "B": {
    "B1": {}
  },
  "foo": {
    "_": "_"
  }
}

将按照以下方式打印内容: ["A","A1","foo"],["foo"]

would print something along the lines of: ["A","A1","foo"], ["foo"]

不幸的是,我不知道按键将在什么级别嵌套,因此我无法通过简单的选择来弄清楚.我已经接近jq '[paths] | .[] | select(contains(["foo"]))',但是输出包含任何包含foo的树的所有排列. 输出:["A", "A1", "foo"]["A", "A1", "foo", "_"]["foo"][ "foo", "_"]

Unfortunately I don't know at what level of nesting the keys will appear, so I haven't been able to figure it out with a simple select. I've gotten close with jq '[paths] | .[] | select(contains(["foo"]))', but the output contains all the permutations of any tree that contains foo. output: ["A", "A1", "foo"]["A", "A1", "foo", "_"]["foo"][ "foo", "_"]

如果我可以保留原始数据结构格式,但只过滤掉所有不包含键的路径(在这种情况下,"foo"下的子树将不需要隐藏),则奖励.

Bonus points if I could keep the original data structure format but simply filter out all paths that don't contain the key (in this case the sub trees under "foo" wouldn't need to be hidden).

推荐答案

使用您的输入:

$ jq -c 'paths | select(.[-1] == "foo")' 
["A","A1","foo"]
["foo"]

奖励积分:

(1)如果您的jq具有tostream:

(1) If your jq has tostream:

$ jq 'fromstream(tostream| select(.[0]|index("foo")))'

或者更好的是,由于您的输入很大,因此可以将流解析器(jq -n --stream)与该过滤器一起使用:

Or better yet, since your input is large, you can use the streaming parser (jq -n --stream) with this filter:

fromstream( inputs|select( (.[0]|index("foo"))))

(2)您的jq是否具有tostream:

(2) Whether or not your jq has tostream:

. as $in
| reduce (paths(scalars) | select(index("foo"))) as $p
    (null; setpath($p; $in|getpath($p))))

在所有三种情况下,输出均为:

In all three cases, the output is:

{
  "A": {
    "A1": {
      "foo": {
        "_": "_"
      }
    }
  },
  "foo": {
    "_": "_"
  }
}

这篇关于如何使用jq查找到某个键​​的所有路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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