Sanchu Varkey
Sanchu Varkey

Reputation: 47

JQ combine array of json maps based on keys

My json looks like the following

[
  {
    "100": "ONE",
    "200": "TWO"
  },
  {
    "100": "1",
    "200": "2"
  }
]

and I am expecting the following output

{
  "1": "ONE",
  "2": "TWO"
} 

I found few answers here but all have static keys but in my case keys are dynamic

Another example

{
  "apiVersion": "v1",
  "data": {
    "bac6f56f-101c-26da-edfa-c08e6622a337": "1"
  },
  "kind": "ConfigMap",
  "metadata": {
    "annotations": {
      "bac6f56f-101c-26da-edfa-c08e6622a337": "restart"
    },
    "creationTimestamp": "2020-06-25T14:53:06Z",
    "uid": "7b1dfc3a-1357-400e-b750-a1ff98a204b9"
  }
} 

and the expected output is

{"restart":"1"}

Upvotes: 2

Views: 288

Answers (2)

peak
peak

Reputation: 116957

Here's a reduce-free solution to the first problem that hopefully also elucidates the general approach:

.[0] as $dict
| .[1]
| with_entries( {value: $dict[.key], key: (.value|tostring) } )

Solution to second problem

Using the above approach, we have only to tweak the first two lines:

.data as $dict
| .metadata.annotations
| with_entries( {value: $dict[.key], key: (.value|tostring) } )

Upvotes: 1

oguz ismail
oguz ismail

Reputation: 50805

Here is one way:

. as [$V, $K]
| reduce ($K | keys_unsorted)[] as $k ({};
  . + {($K[$k]): $V[$k]}
)

This iterates over the second object's keys, retrieves values associated with each key in both objects, and pairs them in a new one. And can be adapted for your second example by changing

. as [$V, $K]

to

. as {data: $V, metadata: {annotations: $K}}

Online demo

Upvotes: 2

Related Questions