2

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"}
7
  • Are keys always sorted? Commented Jun 24, 2021 at 9:56
  • No that was an example Commented Jun 24, 2021 at 9:57
  • What is the expected output for the above? Commented Jun 24, 2021 at 10:20
  • @Inian added another example and it is an output of kubectl get configmap Commented Jun 24, 2021 at 10:20
  • @Inian {"restart":"1"} Commented Jun 24, 2021 at 10:20

2 Answers 2

2

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

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

Comments

1

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) } )

6 Comments

if I want just a pipe-separated string as output like restart|1 for the second problem, how would you rewrite it. Is it possible?
Yes, of course. One way would be to create the appropriate array(s) and then use join("|").
I piped this to your code | keys[] as $k | "\($k)|\(.[$k])" and it works
Where there's one way, there's usually another :-)
How would you write your way create the appropriate array(s) and then use join("|") ?
|

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.