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

Time:08-30

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.

CodePudding user response:

Short and sweet:

 map_values(first)

CodePudding user response:

Use with_entries, changing each value to the first element of itself:

jq 'with_entries(.value |= .[0])' file.json
  • Related