简体   繁体   English

jq - 当我已经深入到对象的子项中时,如何打印对象的父值?

[英]jq - How do I print a parent value of an object when I am already deep into the object's children?

Say I have the following JSON, stored in my variable jsonVariable . 假设我有以下JSON,存储在我的变量jsonVariable中

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

I parse this JSON with jq using the following: 我使用以下代码使用jq解析此JSON:

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

This would give me the output 这会给我输出

James Brown 詹姆斯布朗

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. 现在,我知道这是一个粗略而简单的例子 - 我正在使用的程序是5或6级深度,除了select之外还有许多不同的JQ函数。 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. 在执行各种过滤方法后,当我已经深入5或6层时,我需要一种方法来选择父项的字段。

Can anyone help? 有人可以帮忙吗? Is there any way of 'going in reverse', back up to the parent? 是否有任何“反向”的方式,回到父母身边? (Not sure if I'm making sense!) (不确定我是否有意义!)

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")'

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 . 您可能希望确保您的选择过滤器仅通过将父级别下​​的所有匹配包装到数组中而在父级别返回一个元素,或者使用unique对最终结果进行重复数据删除。

试一试:

echo $jsonVariable | jq '{Name: .details.name, Id: .Id}  | select(.name == "James Brown")'

Rather than querying up to the value you're testing for, query up to the root object that contains the value you're querying on and the values you wish to select. 您可以查询包含您要查询的值的根对象以及您要选择的值,而不是查询您正在测试的值。

You need the object that contains both the id and the name . 您需要包含idname的对象。

$ jq --arg name 'James Brown' 'select(.details.name == $name).id' input.json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM