Surki Surki - 2 months ago 7
JSON Question

jq: Forming CSV by selectively choosing values from object/embedded array

Input is:

{"1.2.3.4":[{"Value":"myval1","Key":"mykey1"}, {"Value":"myval3","Key":"mykey3"},{"Value":"myval2","Key":"mykey2"},{"Value":"myval4","Key":"mykey4"}]}
{"4.5.6.7":[{"Value":"myval1","Key":"mykey1"}, {"Value":"myval3","Key":"mykey3"},{"Value":"myval2","Key":"mykey2"},{"Value":"myval4","Key":"mykey4"}]}


What I would like to get is:

"1.2.3.4,myval1,myval3"
"4.5.6.7,myval1,myval3"


Basically extract the first field, and then values of "mykey1" and "mykey2" from the embedded value field.

Edit:

What I have tried:

I could extract the values by doing something like below:

jq -c '."1.2.3.4" | .[]' | jq -s 'from_entries | [.mykey1, .mykey2] | join(",")'


I would like to include my object name and as well my object name varies, so I can't really filter by hard coded value

Answer

You could do this:

$ jq -r --argjson cols '["mykey1","mykey2"]' '[to_entries[] | .key, (.value | from_entries[$cols[]])] | @csv' input.json

Converting an object to a list of entries is an easy way to access both the keys and values in the object for your filter.