Flatten a JSON document using jq

This one was a tricky one to craft.

map
(
    with_entries(select(.key != "fields"))
    +
    (.fields | with_entries(.value = .value[0]))
)

Let’s break it down and explain the bits of it

  1. For every item in the array…

    map(...)
    
  2. Create a new object containing the values for all except the fields property.

    with_entries(select(.key != "fields"))
    
  3. Combine that with…

    +
    
  4. Each of the fields projecting each of the values to the first item of each array

    (.fields | with_entries(.value = .value[0]))
    

Leave a Comment