Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions json_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package mergo_test

import (
"bytes"
"encoding/json"
"testing"

"dario.cat/mergo"
)

func TestJsonNumber(t *testing.T) {
jsonSampleData := `
{
"amount": 1234
}
`

type Data struct {
Amount int64 `json:"amount"`
}

foo := make(map[string]interface{})

decoder := json.NewDecoder(bytes.NewReader([]byte(jsonSampleData)))
decoder.UseNumber()
decoder.Decode(&foo)

data := Data{}
err := mergo.Map(&data, foo)
if err != nil {
t.Errorf("failed to merge with json.Number: %+v", err)
}
if data.Amount != 1234 {
t.Errorf("merged amount does not match the json value! expected: 1234 got: %v", data.Amount)
}
}
24 changes: 24 additions & 0 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
package mergo

import (
"encoding/json"
"fmt"
"reflect"
"unicode"
Expand Down Expand Up @@ -111,6 +112,29 @@ func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, conf
return
}
} else {
// If the map side of the merge is a json number then we can use the
// functions on the json number to merge the data depending on the
// destination type.
if number, ok := srcElement.Interface().(json.Number); ok {
switch dstKind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
value, err := number.Int64()
if err != nil {
return fmt.Errorf("...: %+v", err)
}
dstElement.SetInt(value)
continue
case reflect.Float32, reflect.Float64:
value, err := number.Float64()
if err != nil {
return fmt.Errorf("...: %+v", err)
}
dstElement.SetFloat(value)
continue
}
}
// But if we can't do that then fallback to the normal type mismatch
// failure.
return fmt.Errorf("type mismatch on %s field: found %v, expected %v", fieldName, srcKind, dstKind)
}
}
Expand Down