0

I'm trying to range over my map[string]map[string]interface{}

Here is my code below :

var marshallJSON Level
var itemCountAll int64
var itemCountPending int64
var itemCountError int64
var itemCountWarning int64
var itemCountCritical int64
var m []*bson.M

for k, value := range modules {
    for _ , level := range value {
        if level == "err" {
            itemCountError += 1
        }
        if level == "warning" {
            itemCountWarning += 1
        }
        if level == "pending" {
            itemCountPending += 1
        }
    }
    itemCountCritical = itemCountError + itemCountWarning
    itemCountAll = itemCountPending + itemCountCritical
    marshallJSON = Level{All: itemCountAll, Pending: itemCountPending, Critical: itemCountCritical}
    if k != "null" {
        m = append(m, &bson.M{"module": k, "nb_nodes": marshallJSON})
    }
}

An example of the values contained in my variable modules :

{"Module_one":{"host_one":"pending","host_two":"pending"},"Module_two":{"host_three":"err","host_four":"warning","host_five":"pending"}}

I get this output:

[{"module":"Module_one","nb_nodes":{"all":2,"pending":2,"critical":0}},{"module":"Module_two","nb_nodes":{"all":5,"pending":3,"critical":2}}]

I want to have this output :

[{"module":"Module_one","nb_nodes":{"all":2,"pending":2,"critical":0}},{"module":"Module_two","nb_nodes":{"all":3,"pending":1,"critical":2}}]

The problem is that it takes the values calculated for the previous modules and adds them up
My question is how to calculate the number of states per module ?

Filip
  • 19,269
  • 7
  • 51
  • 60
All
  • 43
  • 4

1 Answers1

1

You have to reset the counters before you start the next iteration, so each iteration of the outer loop won't include the previous modules:

for k, value := range modules {
    itemCountError, itemCountWarning, itemCountPending, itemCountCritical,
        itemCountAll = 0, 0, 0, 0, 0

    // ...
}

Or better yet, just declare the counters inside the loop, so they always start from 0 in each iteration:

for k, value := range modules {
    var itemCountError, itemCountWarning, itemCountPending,
        itemCountCritical, itemCountAll int64

    // ...
}

Also note that bson.M is a map, you don't need a pointer to a map (maps are already pointers under the hood), so use:

var m []bson.M
icza
  • 389,944
  • 63
  • 907
  • 827