Skip to content

Commit

Permalink
fix(message): use correct encodings for JSON Number values (#281)
Browse files Browse the repository at this point in the history
  • Loading branch information
shellcromancer authored Dec 2, 2024
1 parent 83bd0e8 commit d476fa5
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
11 changes: 11 additions & 0 deletions message/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"math"
"strings"
"unicode/utf8"

Expand Down Expand Up @@ -366,6 +367,16 @@ func setValue(json []byte, key string, value interface{}) ([]byte, error) {
return sjson.SetBytes(json, key, base64.Encode(v))
}
case Value:
// JSON number values can lose precision if not read with the right encoding.
// Determine if the value is an integer by checking if floating poit truncation has no
// affect of the value.
if v.gjson.Type == gjson.Number {
if v.Float() == math.Trunc(v.Float()) {
return sjson.SetBytes(json, key, v.Int())
}
return sjson.SetBytes(json, key, v.Float())
}

return sjson.SetBytes(json, key, v.Value())
default:
return sjson.SetBytes(json, key, v)
Expand Down
30 changes: 30 additions & 0 deletions transform/object_copy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,36 @@ var objectCopyTests = []struct {
[]byte(`{"a":"b","c":"b"}`),
},
},
{
"large integer",
config.Config{
Settings: map[string]interface{}{
"object": map[string]interface{}{
"source_key": "a",
"target_key": "b",
},
},
},
[]byte(`{"a":30400402455622563}`),
[][]byte{
[]byte(`{"a":30400402455622563,"b":30400402455622563}`),
},
},
{
"large float",
config.Config{
Settings: map[string]interface{}{
"object": map[string]interface{}{
"source_key": "a",
"target_key": "b",
},
},
},
[]byte(`{"a":3.141592653589793}`),
[][]byte{
[]byte(`{"a":3.141592653589793,"b":3.141592653589793}`),
},
},
{
"unescape object",
config.Config{
Expand Down

0 comments on commit d476fa5

Please sign in to comment.