Skip to content

Commit 39e30e5

Browse files
authored
experimental: query: sort keys in json-marshal (#1220)
1 parent 9b26693 commit 39e30e5

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

experimental/apis/data/v0alpha1/query.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package v0alpha1
33
import (
44
"encoding/json"
55
"fmt"
6+
"maps"
7+
"slices"
68
"strconv"
79
"unsafe"
810

@@ -309,7 +311,11 @@ func writeQuery(g *DataQuery, stream *j.Stream) {
309311

310312
// The additional properties
311313
if g.additional != nil {
312-
for k, v := range g.additional {
314+
// we must sort the map-keys to always produce the same JSON
315+
keys := slices.Sorted(maps.Keys(g.additional))
316+
317+
for _, k := range keys {
318+
v := g.additional[k]
313319
stream.WriteMore()
314320
stream.WriteObjectField(k)
315321
stream.WriteVal(v)

experimental/apis/data/v0alpha1/query_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,31 @@ import (
77
"github.com/stretchr/testify/require"
88
)
99

10+
func TestSerializeAdditionalQueryFieldsOrdered(t *testing.T) {
11+
q := DataQuery{
12+
CommonQueryProperties: CommonQueryProperties{
13+
RefID: "A",
14+
MaxDataPoints: 10,
15+
IntervalMS: 500,
16+
},
17+
additional: map[string]any{
18+
"utcOffsetSec": 3600,
19+
"exemplar": false,
20+
"instant": false,
21+
"range": true,
22+
"editorMode": "code",
23+
"legendFormat": "__auto",
24+
},
25+
}
26+
jsonBytes, err := json.Marshal(q)
27+
require.NoError(t, err)
28+
// NOTE: we cannot use require.JSONEq() here,
29+
// because we want to make sure the object-keys
30+
// are ordered
31+
expectedBytes := []byte(`{"refId":"A","maxDataPoints":10,"intervalMs":500,"editorMode":"code","exemplar":false,"instant":false,"legendFormat":"__auto","range":true,"utcOffsetSec":3600}`)
32+
require.Equal(t, expectedBytes, jsonBytes)
33+
}
34+
1035
func TestParseQueriesIntoQueryDataRequest(t *testing.T) {
1136
request := []byte(`{
1237
"queries": [

0 commit comments

Comments
 (0)