Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq map object key value to array of objects containing both

Tags:

json

flatten

jq

I would like to put an object parent key inside the object itself and convert each key value pair to an array

Given:

{
  "field1": {
    "key1": 11,
    "key2": 10
  },
  "field2": {
    "key1": 11,
    "key2": 10
  }
}

Desired output

[
   {"name": "field1", "key1": 11, "key2": 10},
   {"name": "field2", "key1": 11, "key2": 10}
]

I know that jq keys would give me ["field1", "field2"] and jq '[.[]]' would give

[
  { "key1": 11, "key2": 10 },
  { "key1": 11, "key2": 10 }
]

I cannot figure out a way to combine them, how should I go about it?

like image 639
Yavor Lulchev Avatar asked Oct 19 '25 11:10

Yavor Lulchev


2 Answers

Generate an object in {"name": <key>} form for each key, and merge that with the key's value.

to_entries | map({name: .key} + .value)

or:

[keys_unsorted[] as $k | {name: $k} + .[$k]]
like image 65
oguz ismail Avatar answered Oct 22 '25 04:10

oguz ismail


Something like below. Get the list of keys in the JSON using keys[] and add the new field name by indexing key on each object.

jq '[ keys[] as $k | { name: $k } + .[$k] ]'

If you want the ordering of keys maintained, use keys_unsorted[].

like image 31
Inian Avatar answered Oct 22 '25 04:10

Inian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!