-1

Example:

package main

import (
    "encoding/json"
    "fmt"
    "github.com/imdario/mergo"
)

func main() {
    var DATA []map[string]interface{}
    text := []byte(`[{"id":1,"test":1},{"id":2},{"id":3,"test":3},{"test":8}]`)
    err := json.Unmarshal(text, &DATA)
    if err != nil {
        fmt.Errorf("ERR: %s", err)
    }

    var STATE map[string]interface{}
    var newState []interface{}

    fmt.Println("DATA: ", DATA)

    for _, k := range DATA {
        if err := mergo.Merge(&STATE, k, mergo.WithOverride); err != nil {
            fmt.Errorf("Error merge new and old packets: %s", err)
        }
        fmt.Println("STATE: ", STATE)

        newState = append(newState, STATE)
    }

    fmt.Println(newState)

}

I get: [map[id:3 test:8] map[test:8 id:3] map[id:3 test:8] map[test:8 id:3]]
I want get [map[id:1 test:1] map[test:2 id:1] map[id:3 test:3] map[test:8 id:3]]

I can not understand why the last value falls into the data slice, and not what was at the time of writing

batazor
  • 852
  • 2
  • 16
  • 36

1 Answers1

0

I realized what the problem is, I need to explicitly copy each value

for key,value := range STATE {
    newState[i][key] = value
}
batazor
  • 852
  • 2
  • 16
  • 36