jttout
jttout

Reputation: 23

Build string from variable-depth nested JSON values

I'm attempting to follow all branches in a tree-styled JSON object to create one long, concatenated string from each branch. The number of children and the maximum depth per node are unknown, so the result must be generalized to any amount.

The data I'm working with is similar to the following:

{
    "name":"root",
    "children": [
        {
            "name":"foo",
            "children":[
                {
                    "name":"bar",
                    "children":[]
                },
                {
                    "name":"baz",
                    "children":[]
                }
            ]
        },
        {
           "name":"zoo",
            "children": [
                {
                    "name":"zar",
                    "children": [
                        {
                            "name":"zaz",
                            "children": []
                        }   
                    ]
                }
            ]
        }
    ]
}

I came close in this jqplay example.

You can see this works in the naive case where there is only a single child. Where I'm most confused is how to "reset" the parent in the scenarios of multiple children. Instead of recursing
root -> foo -> bar -> baz
I'd want
root -> foo -> bar
root -> foo -> baz

Desired output from the jqplay above:
"root/foo/bar" "root/foo/baz" "root/zoo/zar/zaz"

I would prefer a pure jq solution, a general Bash solution would also work.

Upvotes: 2

Views: 179

Answers (1)

peak
peak

Reputation: 116740

Since your data structure is recursive, a recursive helper function is what's needed here:

def flat:
  [.name] + (.children[] // {} | if has("name") then flat else [] end);


flat | join("/") 

With your input, the output using jq -r would be:

root/foo/bar
root/foo/baz
root/zoo/zar/zaz

Upvotes: 0

Related Questions