0

I would like to make (using jq) from input:

{ key1: value1, key2: value2, key3: [ {key4: value3, key5: value5}, {key4: value4, key5: value6}, . . . {key4: valueN, key5: valueM}, . . . ] } 

this output:

{ key1: value1, key2: value2, value3: value5, value4: value6, . . . valueN: valueM, . . . } 

How to do it?

I have tried some ways, but I haven't able to find the proper solution, mainly jq generated separated objects, I would like to have only one output object containing keys from input object.

4
  • What is the logic here? how would you identify all the key/value pairs? do they all start with a common prefix? e.g. like key in your above example Commented Aug 16, 2022 at 7:43
  • Are the sub objects present under key3 always? Commented Aug 16, 2022 at 7:44
  • Sorry, I have edited the input object, key4 and key5 are fix. Commented Aug 16, 2022 at 7:45
  • Maybe I described to issue wrongly (frankly, I don't see where is the different), but my solution for the problem was that: [{"": .vulnerabilities[] | {"key" : .cveId, "value": .description} } | add] | from_entries Commented Aug 16, 2022 at 13:34

3 Answers 3

2

For the given input, the following should produce the desired output

.key3 as $t | del(.key3) | . + ( $t | map(to_entries | { (.[0].value) : .[1].value } ) | add ) 

jq-play link

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

Comments

2

I would use a reduce on .key3's items and append them successively:

reduce .key3[] as {$key4, $key5} (del(.key3); .[$key4] = $key5) 
{ "key1": "value1", "key2": "value2", "value3": "value5", "value4": "value6", "valueN": "valueM" } 

Demo

2 Comments

nice trick +1, but one reason I always leave out using reduce for fairly simpler solutions is the readability perspective. It gets tricky for new users to tweak it, if need for further changes
@Inian I agree that it might be harder to read for some (especially those used to other paradigms) but readability in general is a matter of familiarity with such concepts, so introducing them (especially to those coming from other paradigms) infact improves familiarity and, with it, readability, especially when having multiple solutions to the same problem to compare with (as we do here). So, thank you for your contribution as well! :)
0

key3 almost has the format that from_entries uses, tweak it?

.key3 | map(.key = .key4) | map(.value = .key5) | map( del(.key4,.key5) ) 

Converts key3 array to:

[ { "key": "value3", "value": "value5" }, { "key": "value4", "value": "value6" }, { "key": "valueN", "value": "valueM" } ] 

Pipe to from_entries:

( ... | from_entries) as $obj | . + $obj | del(.key3) 

Output:

{ "key1": "value1", "key2": "value2", "value3": "value5", "value4": "value6", "valueN": "valueM" } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.