skip to Main Content

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

2

Answers


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

    map({key: .name, value: .id}) | from_entries
    
    Login or Signup to reply.
  2. Here’s another way:

    map({(.name): .id}) | add
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search