jq-当我已经深入对象的子级时,如何打印该对象的父级值? [英] jq - How do I print a parent value of an object when I am already deep into the object's children?

查看:87
本文介绍了jq-当我已经深入对象的子级时,如何打印该对象的父级值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下JSON,存储在我的变量 jsonVariable 中.

Say I have the following JSON, stored in my variable jsonVariable.

{
    "id": 1,
    "details": {
        "username": "jamesbrown",
        "name": "James Brown"
    }
}

我使用以下命令通过jq解析此JSON:

I parse this JSON with jq using the following:

echo $jsonVariable | jq '.details.name | select(.name == "James Brown")'

这会给我输出

詹姆斯·布朗

但是,如果我也想获得此人的身份证怎么办?现在,我知道这是一个粗略而简单的示例-目前正在使用的程序深度为5或6级,除了select以外还具有许多其他JQ函数.在执行各种过滤方法后,当我已经深达5或6层时,我需要一种选择家长字段的方法.

But what if I want to get the id of this person as well? Now, I'm aware this is a rough and simple example - the program I'm working with at the moment is 5 or 6 levels deep with many different JQ functions other than select. I need a way to select a parent's field when I am already 5 or 6 layers deep after carrying out various methods of filtering.

任何人都可以帮忙吗?有什么办法可以逆转",回到父母身边吗? (不确定我是否有意义!)

Can anyone help? Is there any way of 'going in reverse', back up to the parent? (Not sure if I'm making sense!)

推荐答案

对于更通用的方法,将"parent"元素的值保存在所需的详细信息级别,然后将其通过管道传递到过滤器的末尾:

For a more generic approach, save the value of the "parent" element at the detail level you want, then pipe it at the end of your filter:

jq '. as $parent | .details.name | select(. == "James Brown") | $parent'

当然,对于您暴露的琐碎情况,您可以完全省略:

Of course, for the trivial case you expose, you could omit this entirely:

jq 'select(.details.name == "James Brown")'

此外,请考虑,如果您选择的过滤器为单个父对象返回许多匹配项,则您将为每个匹配项收到一个父对象的副本.您可能希望通过将父级以下的所有匹配项包装到数组中,或使用unique对最终结果进行重复数据删除,以确保您选择的过滤器仅在父级返回一个元素.

Also, consider that if your selecting filters return many matches for a single parent object, you will receive a copy of the parent object for each match. You may wish to make sure your select filters only return one element at the parent level by wrapping all matches below parent level into an array, or to deduplicate the final result with unique.

这篇关于jq-当我已经深入对象的子级时,如何打印该对象的父级值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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