1

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.

2 Answers 2

2

Short and sweet:

 map_values(first)
Sign up to request clarification or add additional context in comments.

3 Comments

Love the most elegant, thanks for sharing.
Almost 50% shorter, yet nowhere near that elegance: .[]|=.[0]
If elegance is in the eye of the beholder, shortness must be in the eye of the metric.
1

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

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

1 Comment

Super, that makes sense, I didn't even realize that. Live and learn, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.