Skip to content

feat(map): Handle json.Number when merging maps #261

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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