4

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?

2 Answers 2

7

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]]
Sign up to request clarification or add additional context in comments.

Comments

2

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[].

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.