Skip to content

Commit d476fa5

Browse files
author
Daniel Stinson-Diess
authored
fix(message): use correct encodings for JSON Number values (#281)
1 parent 83bd0e8 commit d476fa5

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

message/message.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"bytes"
66
"encoding/json"
77
"fmt"
8+
"math"
89
"strings"
910
"unicode/utf8"
1011

@@ -366,6 +367,16 @@ func setValue(json []byte, key string, value interface{}) ([]byte, error) {
366367
return sjson.SetBytes(json, key, base64.Encode(v))
367368
}
368369
case Value:
370+
// JSON number values can lose precision if not read with the right encoding.
371+
// Determine if the value is an integer by checking if floating poit truncation has no
372+
// affect of the value.
373+
if v.gjson.Type == gjson.Number {
374+
if v.Float() == math.Trunc(v.Float()) {
375+
return sjson.SetBytes(json, key, v.Int())
376+
}
377+
return sjson.SetBytes(json, key, v.Float())
378+
}
379+
369380
return sjson.SetBytes(json, key, v.Value())
370381
default:
371382
return sjson.SetBytes(json, key, v)

transform/object_copy_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,36 @@ var objectCopyTests = []struct {
3232
[]byte(`{"a":"b","c":"b"}`),
3333
},
3434
},
35+
{
36+
"large integer",
37+
config.Config{
38+
Settings: map[string]interface{}{
39+
"object": map[string]interface{}{
40+
"source_key": "a",
41+
"target_key": "b",
42+
},
43+
},
44+
},
45+
[]byte(`{"a":30400402455622563}`),
46+
[][]byte{
47+
[]byte(`{"a":30400402455622563,"b":30400402455622563}`),
48+
},
49+
},
50+
{
51+
"large float",
52+
config.Config{
53+
Settings: map[string]interface{}{
54+
"object": map[string]interface{}{
55+
"source_key": "a",
56+
"target_key": "b",
57+
},
58+
},
59+
},
60+
[]byte(`{"a":3.141592653589793}`),
61+
[][]byte{
62+
[]byte(`{"a":3.141592653589793,"b":3.141592653589793}`),
63+
},
64+
},
3565
{
3666
"unescape object",
3767
config.Config{

0 commit comments

Comments
 (0)