0

Consider the following JSON having a list of key-value pairs

{
  "session1": 128,
  "session2": 1048596,
  "session3": 3145728,
  "session4": 3145828,
  "session5": 11534338,
  "session6": 11544336,
  "session7": 2097252
}

The value is number of bytes

I want to print sum of values by range - the ranges being (lower bound included, high bound excluded); 0-1MB, 1-2MB, 2-3MB, ... 12-13MB.

 1MB =  1048576
 2MB =  2097152
 3MB =  3145728
 4MB =  4194304
 5MB =  5242880
 6MB =  6291456
 7MB =  7340032
 8MB =  8388608
 9MB =  9437184
10MB = 10485760
11MB = 11534336
12MB = 12582912
13MB = 13631488

The expected output is

{
  "0-1MB": 128,
  "1-2MB": 1048596,
  "2-3MB": 2097252,
  "3-4MB": 6291556,
  "11-12MB": 23078674
}

The above is just representative, suggestions are welcome (like having the value output in human readable format).

1 Answers1

1

In analogy to your other question, iterate over the values before dividing, and add them instead of 1:

reduce (map(.) | sort[]) as $n ({}; .[$n / 1048576 | floor | "\(.)-\(.+1)MB"] += $n)
{
  "0-1MB": 128,
  "1-2MB": 1048596,
  "2-3MB": 2097252,
  "3-4MB": 6291556,
  "11-12MB": 23078674
}

Demo

pmf
  • 24,478
  • 2
  • 22
  • 31
  • Thanks @pmf. This gives me what I was after. The only change I had to make was add `+1` `reduce (map(.) | sort[]) as $n ({}; .[$n / 1048576 | floor | "\(.)-\(.+1)MB"] += $n)` – Jojo Thomas Jul 30 '23 at 17:09
  • 1
    @JojoThomas Good spotting! This must have slipped through when simplifying the code. I am going to correct it in the answer. – pmf Jul 30 '23 at 17:10