0

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

1
  • what you have tried? Commented Sep 21, 2016 at 15:31

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If you really want "1.2.3.4,myval1,myval3" instead of "1.2.3.4","myval1","myval3", then use [join(",")] | @csv instead of just @csv
0

Here is another solution which generalizes Surki's approach:

  keys[] as $k
| .[$k]
| from_entries
| [$k, .mykey1, .mykey2]
| join(",")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.