1

Gathering all root to leaf values along every path in a tree-like json object with JQ. It seems like this should be easy with the walk or flatten functions, but I can't figure it out despite some helpful questions that have already been asked.

I have this

 {
     "cond1":["a","b","c"],
     "cond2":["a1","b2","c"],
     "cond2":["a","b","c3"]    
 }    

I want this

["cond1","a"]
["cond1","b"]
["cond1","c"]
["cond2","a1"]
["cond2","b2"]
["cond2","c"]
["cond2":"a"]
["cond2":"b"]
["cond2":"c3"]

Similar questions: https://github.com/stedolan/jq/issues/646 jq - How do I print a parent value of an object when I am already deep into the object's children?

Also, how would the answer be different if instead of ["a","b","c"] the array consisted on nested objects i.e. [["x2","x3"],["x1,"x2"]]

peak
  • 105,803
  • 17
  • 152
  • 177
tjb
  • 11,480
  • 9
  • 70
  • 91

1 Answers1

2

The key to answering both questions is paths. For example, the following filter produces the desired output in the first case:

paths as $p
| getpath($p)
| select(scalars)
| ($p | map(select(type=="string"))) + [.]

The same filter can be used with any valid JSON as input. Replacing .cond2 with a valid nested array along the lines shown in the Q, the output would be:

["cond1","a"]
["cond1","b"]
["cond1","c"]
["cond2","x2"]
["cond2","x3"]
["cond2","x1"]
["cond2","x2"]
peak
  • 105,803
  • 17
  • 152
  • 177