Skip to content

Commit

Permalink
Use json.Number when scan to JSONMap (#202)
Browse files Browse the repository at this point in the history
* Use json.Number when scan to JSONMap

* Add unittest for scanning JSONMap using json.Decoder.UseNumber
  • Loading branch information
levanlongktmt authored Apr 11, 2023
1 parent 8e2e3c6 commit 56bb801
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
6 changes: 5 additions & 1 deletion json_map.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package datatypes

import (
"bytes"
"context"
"database/sql/driver"
"encoding/json"
Expand Down Expand Up @@ -42,7 +43,10 @@ func (m *JSONMap) Scan(val interface{}) error {
return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", val))
}
t := map[string]interface{}{}
err := json.Unmarshal(ba, &t)
rd := bytes.NewReader(ba)
decoder := json.NewDecoder(rd)
decoder.UseNumber()
err := decoder.Decode(&t)
*m = t
return err
}
Expand Down
10 changes: 10 additions & 0 deletions json_map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,3 +172,13 @@ func TestJSONMap(t *testing.T) {
}
}
}

func TestJSONMap_Scan(t *testing.T) {
content := `{"user_id": 1085238870184050699, "name": "Name of user"}`
obj := make(datatypes.JSONMap)
err := obj.Scan([]byte(content))
if err != nil {
t.Fatalf("decode error %v", err)
}
AssertEqual(t, obj["user_id"], 1085238870184050699)
}

0 comments on commit 56bb801

Please sign in to comment.