使用jq查询子节点时返回其父节点

5

想知道在查询子“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' - riteshtch
@ritesht93 我在我的 Mac 上使用那个命令只是得到了一个 grep 用法帮助文本。 - Marty
2个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
2

原问题中的筛选器已经接近解决方案。需要做的只是重新排列放在 select 中的内容。例如:

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

2
过滤器:
.. | objects | select(.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' 成功了,谢谢。 - Marty

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,