Skip to content

Commit 575f7be

Browse files
Use json.Number when UnmarshalJSON'ing to JSONMap (#313)
PR #202 made an equivalent change to .Scan() previously: commit 56bb801 Author: Long Le <levanlongktmt@gmail.com> Date: Tue Apr 11 10:17:44 2023 +0700 Use json.Number when scan to JSONMap (#202) This commit makes the equivalent change to .UnmarshalJSON, so that the value is consistently correct whether it originates in the database or in a JSON object to be decoded. This commit also adds a test validating that, which fails without this commit: $ go test ./... 2025/10/23 16:06:37 testing sqlite3... --- FAIL: TestJSONMap_Unmarshal (0.00s) utils.go:40: datatypes/json_map_test.go:193: expect: 1085238870184050699, got 1085238870184050688 but passes with this commit. Co-authored-by: Jeff Smith <toxicglados@gmail.com>
1 parent 22a6ae2 commit 575f7be

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

json_map.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,10 @@ func (m JSONMap) MarshalJSON() ([]byte, error) {
6363
// UnmarshalJSON to deserialize []byte
6464
func (m *JSONMap) UnmarshalJSON(b []byte) error {
6565
t := map[string]interface{}{}
66-
err := json.Unmarshal(b, &t)
66+
rd := bytes.NewReader(b)
67+
decoder := json.NewDecoder(rd)
68+
decoder.UseNumber()
69+
err := decoder.Decode(&t)
6770
*m = JSONMap(t)
6871
return err
6972
}

json_map_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,16 @@ func TestJSONMap_Scan(t *testing.T) {
183183
AssertEqual(t, obj["user_id"], 1085238870184050699)
184184
}
185185

186+
func TestJSONMap_Unmarshal(t *testing.T) {
187+
content := `{"user_id": 1085238870184050699, "name": "Name of user"}`
188+
obj := make(datatypes.JSONMap)
189+
err := obj.UnmarshalJSON([]byte(content))
190+
if err != nil {
191+
t.Fatalf("decode error %v", err)
192+
}
193+
AssertEqual(t, obj["user_id"], 1085238870184050699)
194+
}
195+
186196
// TestJSONMapValueType tests the return type from JSONMap Value() method
187197
func TestJSONMapValueType(t *testing.T) {
188198
// Test JSONMap

0 commit comments

Comments
 (0)