0

I'm trying to build up an array of times from a set of JSON data and was hoping to do it with jq without having to write code in another language to do the processing.

The Data

[
    {
        "id": "abc",
        "time": 34
    },
    {
        "id": "def",
        "time": 25
    },
    {
        "id": "abc",
        "time": 45
    }
]

I'd like to get the output in the format of

{
    "abc": [ 34, 45 ],
    "def": [ 25 ]
}

2 Answers 2

2

Here is one way to do it.

jq 'reduce .[] as $i ({}; .[$i.id] += ($i|[.time]))'
1

A functional (reduce-free) approach using only jq builtins:

group_by(.id)
| map( {(.[0]|.id): (map([.time]) | add)} )

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.