2

Let's say I have some JSON that looks like:

[
    {"foo": "apple", "bar": 42},
    {"foo": "pear", "bar": 13},
    {"foo": "apple", "bar": 666}
]

How can I transform it into something like:

{
   "apple": [42, 666],
   "pear": [13],
}

grouping the bars by the foos?

So far, I've tried using jq's group_by(...) function which gave me:

[
  [{"foo": "apple", "bar": 42}, {"foo": "apple", "bar": 666}],
  [{"foo": "pear", "bar": 13}]
]

which is a start but not exactly what I'm looking for.

0

2 Answers 2

2

A simple and efficient solution would avoid group_by, the implementation of which currently entails a sorting operation:

reduce .[] as $x ({}; .[$x.foo] += [$x.bar])
Sign up to request clarification or add additional context in comments.

Comments

2

You could use group_by and do the transformation after that, i.e. form the key with .foo and add all the .bar's

group_by(.foo)[] | { (.[0].foo): [.[].bar] }

jqplay - demo

Comments

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.