如何访问任何级别的密钥?

How to access key at any level?

我有这个输入文件

{
    "description": "this is a fake description",
    "owner": "john",
    "region": "us-east-1",
    "topics": {
        "For collecting responses for prod1": {
            "suffix_name": "response-to-hogwarts.fifo",
            "tags": {}
        }
    },
    "queues": {
        "For collecting responses and requests from test1": {
            "suffix_name": "rr_sf_name.fifo",
            "tags": {}
        },
        "For collecting responses for test2": {
            "suffix_name": "response-to-hogwarts.fifo",
            "tags": {}
        }
    },
    "subscriptions": {
        "For receiving harry_potter requests": {
            "topic": {
                "suffix_name": "harry_potter.fifo",
                "tag": "staging"
            },
            "queue": {
                "suffix_name": "rr_sf_name.fifo"
            }
        },
        "For receiving harry_potter requests from test3": {
            "topic": {
                "suffix_name": "harry_potter.fifo",
                "tag": "harry_potter_hogwarts"
            },
            "queue": {
                "suffix_name": "rr_sf_name.fifo"
            }
        },
        "For receiving demo requests": {
            "topic": {
                "suffix_name": "demo.fifo",
                "tag": "staging"
            },
            "queue": {
                "suffix_name": "rr_sf_name.fifo"
            }
        },
        "For receiving demo requests from test4 through connector": {
            "topic": {
                "suffix_name": "demo.fifo",
                "tag": "harry_potter_hogwarts"
            },
            "queue": {
                "suffix_name": "rr_sf_name.fifo"
            }
        },
        "For receiving testing responses for hogwarts": {
            "topic": {
                "suffix_name": "response-to-hogwarts.fifo"
            },
            "queue": {
                "suffix_name": "response-to-hogwarts.fifo"
            }
        }
    }
}

现在我想从 ALL suffix_name 字段的任何级别

的值中删除“.fifo”后缀

示例输出(为简洁起见被截断)

    "topics": {
        "For collecting responses for prod1": {
            "suffix_name": "response-to-hogwarts",
            "tags": {}
        }
    },

现在我想到了这个,对我有用

.queues |= with_entries(.value.suffix_name |= sub(".fifo";""))
| .topics |= with_entries(.value.suffix_name |= sub(".fifo";""))
| .subscriptions |= with_entries(.value |= with_entries(.value |= with_entries(.value |= rtrimstr(".fifo"))))

我想知道,是否有更好的方法,使用递归或其他方法来解析所有键,如果键是 suffix_name,trim 来自值。

您可以使用 walk:

walk(if type=="object" and .suffix_name 
     then .suffix_name |= sub("[.]fifo$";"") else . end)

或者,只需使用 |=:

 (.. | select(type == "object" and .suffix_name) | .suffix_name) 
  |=  sub("[.]fifo$";"") 

使用 path 函数替代 walk - getpathsetpath

reduce ( paths | select(.[-1] | endswith("suffix_name")? ) ) as $p 
  ( .; setpath($p; getpath($p) | sub("[.]fifo$";"") ) )

确定从根到 suffix_name 的路径并使用 reduce 对其进行迭代。对于每个路径,通过删除后缀重建值。