Search code examples
arraysjsonjqflatten

Convert json single-item arrays to objects using bash/jq


Given the example JSON below:

{
  "account_number": [
    "123456"
  ],
  "account_name": [
    "name"
  ],
  "account_id": [
    654321
  ],
  "username": [
    "demo"
  ]
}

I'd like to get:

{
  "account_number": "123456",
  "account_name": "name",
  "account_id": 654321,
  "username": "demo"
}

Currently, I'm brute forcing it with | sed 's/\[//g' | sed 's/\]//g' | jq '.' ... but of course, that's ugly and causes issues if any of the values contain [ or ].

I've been unsuccessful with jq's flatten and other loops and mapping techniques like | jq -s '{Item:.[]} | .Item |add' to try and flatten the single-item arrays. Ideally, it would work where it would flatten arrays [...] to flat elements/objects {...}. Either way something better than replacing all occurrences of square brackets.


Solution

  • Short and sweet:

     map_values(first)