How to use jq to find all paths to a certain key

前端 未结 1 1537
梦谈多话
梦谈多话 2021-01-04 13:05

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

ex:

{
  \"A\": {
    \"A1\": {
      \"foo\": {
               


        
相关标签:
1条回答
  • 2021-01-04 13:42

    With your input:

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

    Bonus points:

    (1) If your jq has tostream:

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

    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) 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": {
        "_": "_"
      }
    }
    
    0 讨论(0)
提交回复
热议问题