sx7mac
sx7mac

Reputation: 37

JQ - Recursive JSON return parent

I'm tryng to return a parent in this kind of json using JQ:

{
    "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": []
                            }
                        
                        ]
                    }
                ]
            }
        ]
    }
}

The goal is to retrieve the parent text for an element. For example:

This code doesn't work: .all | .children[] as $parent | select(.children[].text == "acca" ) | $parent.text

Someone can help me? Thanks! :)

Upvotes: 1

Views: 659

Answers (2)

oguz ismail
oguz ismail

Reputation: 50775

This is easy. Get the path to the string you're looking for, retrieve the path to its grand grandparent out of it, and extract text from there.

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

Online demo

Upvotes: 1

peak
peak

Reputation: 116790

Here's a succinct, parameterized solution that does not require explicit use of recurse:

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

Example usage:

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

(Notice that there might not be any need to quote the "needle".)

Upvotes: 1

Related Questions