【问题标题】:JQ - Recursive JSON return parentJQ - 递归 JSON 返回父级
【发布时间】:2021-03-15 13:58:21
【问题描述】:

我正在尝试使用 JQ 在这种 json 中返回父级:

{
    "all" : {
        "text": "a",
        "children": [
            {
                "text": "aa",
                "children": []
            },
            {
                "text": "ab",
                "children": []
            },
            {
                "text": "ac",
                "children": [
                    {
                        "text": "aca",
                        "children": []
                    },
                    {
                        "text": "acb",
                        "children": []
                    },
                    {
                        "text": "acc",
                        "children": [
                            {
                                "text": "acca",
                                "children": []
                            }
                        
                        ]
                    }
                ]
            }
        ]
    }
}

目标是检索元素的父文本。 例如:

  • 搜索 acca --> acc
  • 正在搜索 acc --> ac

此代码不起作用: .all | .children[] as $parent | select(.children[].text == "acca" ) | $parent.text

有人可以帮助我吗? 谢谢! :)

【问题讨论】:

    标签: json jq parent recursive-datastructures


    【解决方案1】:

    这很容易。获取您要查找的字符串的路径,从中检索到其祖父母的路径,然后从那里提取text

    getpath(
      paths(strings
        | select(. == "acca")
      )[:-3]
    ) .text
    

    Online demo

    【讨论】:

      【解决方案2】:

      这是一个简洁的参数化解决方案,不需要显式使用recurse

      paths(objects | select(.text == $needle)) as $p
      | getpath($p[:-2]).text
      

      示例用法:

      jq --arg needle acca -f program.jq input.json
      

      (请注意,可能不需要引用“针”。)

      【讨论】:

      • 伙计,我完全忘记了paths
      • 隐式使用了recurse 吗?使用recurse有什么顾虑吗?
      • 是的,也不是(或者如果你愿意,也不是)。 “否”的原因是 recurse 的定义方式受益于 jq 的 TCO(尾调用优化)。
      猜你喜欢
      • 2020-02-11
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 2020-11-11
      • 2020-09-07
      相关资源
      最近更新 更多