Reputation: 3357
My data consists of categories
containing elements
. Expressed in .csv format, data about the category is repeated with each element. I want to avoid this by storing the data in a .json tree format instead.
How might I consolidate this array of elements
…
[
{
"category": "a",
"comment": "the repetition, oh my",
"element_foo": 1,
"element_bar": 10
},
{
"category": "a",
"comment": "the repetition, oh my",
"element_foo": 2,
"element_bar": 20
}
],
…into this array of categories
containing arrays of elements
?
[
{
"category": "a",
"comment": "the repetition, oh my",
"elements": [
{
"foo": 1,
"bar": 10
},
{
"foo": 2,
"bar": 20
}
]
}
]
I'm hoping this is something fairly trivial for jq
to do - otherwise I'll write something more heavyweight.
Upvotes: 0
Views: 79
Reputation: 134861
Group the objects by category and comment, then map the groupings as you'd like:
group_by({ category, comment }) | map({
category: .[0].category,
comment: .[0].comment,
elements: map({
foo: .element_foo,
bar: .element_bar
})
})
Upvotes: 3