【问题标题】:Return parent node with jq while querying one of its children使用 jq 返回父节点,同时查询其子节点之一
【发布时间】:2016-06-01 04:41:35
【问题描述】:

想知道在查询子“Id”时是否可以从下面的 json 中返回父“Id”

{
    "DistributionList": {
        "Items": [
            {
                "Origins": {
                    "Items": [
                        {
                            "Id": "abc"
                        }
                    ],
                    "Quantity": 1
                },
                "Id": "parent123"
            },
            {
                "Origins": {
                    "Items": [
                        {
                            "Id": "def"
                        }
                    ],
                    "Quantity": 1
                },
                "Id": "parent345"
            }
         ]
    }
}

例如。如果我查询子 ID“abc”,它应该返回“parent123”。

做类似的事情:

more jsonfile | jq '.DistributionList.Items[].Origins.Items[] | select(.Id == "abc") | .Id'

只会返回 "abc" -> 但我需要父 ID。 不知道是否有办法用 jq 做到这一点

【问题讨论】:

  • 不使用jq这样的东西怎么样:grep -oP '(?<=Id":)\s*".*$' data.txt | sed -n 's/^/child: /;N;s/\n/ has parent Id: /;p'
  • @ritesht93 我只是在我的 mac 下使用该命令获取 grep 使用帮助文本

标签: json bash shell unix jq


【解决方案1】:

原始问题中的过滤器接近解决方案。所需要的只是重新排列select 中的内容。例如

  .DistributionList.Items[]
| select(.Origins.Items[].Id == "abc")
| .Id

【讨论】:

    【解决方案2】:

    过滤器: .. |对象 |选择(.Origins.Items[]? | .Id == "abc") | .id

    产生:

    "parent123"
    

    您可能想要参数化过滤器,例如:

    def parent(child):
     .. | objects | select( .Origins.Items[]? | .Id == child) | .Id ;
    

    【讨论】:

    • more filename | jq '.. | objects | select(.Origins.Items[]? | .Id == "xxx") | .Id' 成功了,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多