1

I have a JSON file like this:

{
    "cases": [
        {"id": "1", "count": 2, "ignore": "f"},
        {"id": "2", "count": 7, "ignore": "o"},
        {"id": "3", "count": 11, "ignore": "o"}
    ]
}

Doing jq '.cases[] | { "\(.id)" : .count }' test.json gives

{
  "1": 2
}
{
  "2": 7
}
{
  "3": 11
}

but I need

{ 
  "1": 2, 
  "2": 7, 
  "3": 11 
}

How can I get there?

peak
  • 105,803
  • 17
  • 152
  • 177
Felix Dombek
  • 13,664
  • 17
  • 79
  • 131

3 Answers3

3

You need to collect the results into an array and add them

.cases | map({ "\(.id)" : .count }) | add
Inian
  • 80,270
  • 14
  • 142
  • 161
2

from_entries sounds like the obvious choice. First map your input array to an array of key-value pairs, then construct an object from this array:

.cases | map({ key: .id, value: .count }) | from_entries
knittl
  • 246,190
  • 53
  • 318
  • 364
2

Here's an approach using reduce which iteratively builds up the result object:

reduce .cases[] as {$id, $count} ({}; .[$id] = $count)

Demo

pmf
  • 24,478
  • 2
  • 22
  • 31