0

Using JQ how do I convert array of objects to key-value pair object?

Given the JSON:

[
  {
    "name": "foo",
    "id": "123"
  },
  {
    "name": "bar",
    "id": "456"
  }
]

Desired output:

{
  "foo": "123",
  "bar": "456"
}

1 Answer 1

2

You can convert to an array of objects with key and value keys, then use from_entries:

map({key: .name, value: .id}) | from_entries
7
  • How do I get output to be: ` { "foo: 123", "bar: 456" } ' Commented Jul 3 at 1:28
  • @user1822391 There's a flag for compact output, --compact-output (or -c), but it'll remove all whitespace. Commented Jul 3 at 17:53
  • @user1822391 Or maybe I misunderstood your question. The JSON in your comment isn't valid. Commented Jul 3 at 17:54
  • Sorry I meant how do I get the output to format as name: id, as in { "foo": "123", "bar": "456" } Commented Jul 4 at 0:30
  • @user1822391 That's what the command does, no? See this playground. Commented Jul 4 at 14:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.