It's probably not the most elegant of solutions as I'm still learning jq
, but this produces your desired output
jq -r '.[].results[] | { a:.[0], b:.[1][] } | [ .a, .b ] | @csv'
Results
"sm-clust001","163slesm02"
"sm-clust001","163slesm01"
"sm-cssl112","ucsbnchac240"
"sm-cssl112","ucsbnchac209"
"sm-cssl112","ucsbnchac241"
"sm-cssl112","ucsbnchac242"
The "magic" is in the second part of the pipeline, { a:.[0], b:.[1][] }
, which repeats the first item ([0]
) for each one of the second items ([1][]
). This can then be converted to a list of arrays and thence output as CSV.
In order to handle the last line of example data you recently added, I've modified the pipeline to convert this outlier into the same shape as the other data. (This is also a learning exercise for me.)
jq -r '
.[].results[] | # Concentrate only on the results[] array
[ .[0], [ .[1][]? // .[1] ] ] | # Copy through first element; force the second to be an array
{ a:.[0], b:.[1][] } | # Iterate across the second element as an array
[ .a, .b ] | # Convert the objects we have just created back into array slices
@csv # Output as CSV, remember the -r flag for jq
'
The addition here is the [ .[0], [ .[1][]? // .[1] ] ]
component, which passes through the first element of each block unchanged, and then if the second element is not an array converts it to one. (It unwraps the array, or presents the singleton item, and then wraps the result into an array.)
It has also been pointed out that I could have modified my original code to provide a more elegant solution by using (.[1][]? // .[1])
to contain an if/then expression that either iterates across the array elements as before, or simply provides that second element if it's not an array:
jq -r '.[].results[] | { a:.[0], b:(.[1][]? // .[1]) } | [ .a, .b ] | @csv'
Results of either modification
"sm-clust001","163slesm02"
"sm-clust001","163slesm01"
"sm-cssl112","ucsbnchac240"
"sm-cssl112","ucsbnchac209"
"sm-cssl112","ucsbnchac241"
"sm-cssl112","ucsbnchac242"
"ASite","unixhost1123"
I've been learning a lot from this tutorial, which so far has been one of the better ones I've found.