0

Given I have a list of objects:

{
  "alpha": {
    "bytes": {
      "value": 4789440
    },
    "doc_count": 7723
  },
  "beta": {
    "bytes": {
      "value": 4416862639
      },
    "doc_count": 1296
  }
}

Is there a way using jq to get an array representation of this, such as:

  [
    {
      "key": "alpha",
      "bytes": {
        "value": 4789440
      },
      "doc_count": 7723
    },
    {
      "key": "beta",
      "bytes": {
        "value": 4416862639
      },
      "doc_count": 1296
    }
  ]
2
  • Neither of your desired output formats are valid JSON (fields only exist in objects such as {"a":1}, not in arrays (["a":1] is not valid). You can, however, have an array of objects [{"a":1},{"b":2}] if this is what you want. Commented Jan 19, 2022 at 14:04
  • @pmf You are totally right, sorry for that... I have updated the question with a correct example result. Commented Jan 19, 2022 at 14:08

2 Answers 2

3

Using to_entries would be one way. By accessing .key and .value, the composition would be:

jq '[to_entries[] | {key} + .value]' input.json
[
  {
    "key": "alpha",
    "bytes": {
      "value": 4789440
    },
    "doc_count": 7723
  },
  {
    "key": "beta",
    "bytes": {
      "value": 4416862639
    },
    "doc_count": 1296
  }
]

Demo

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

Comments

1
[ keys_unsorted[] as $key | { $key } + .[$key] ]

Demo on jqplay

or

to_entries | map( { key } + .value )

Demo on jqplay

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.