From 56fd8a1e4a910a35399b1062a3d452b0bb1000fe Mon Sep 17 00:00:00 2001 From: AVejahat Date: Fri, 3 May 2024 19:07:49 +0200 Subject: [PATCH] bugfix: add missing comma in vector/matrix array (#14047) * bugfix: Add missing comma when encoding JSON results in web API --------- Signed-off-by: Amir Vejahat Co-authored-by: Arthur Silva Sens --- web/api/v1/json_codec.go | 10 ++++++++-- web/api/v1/json_codec_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/web/api/v1/json_codec.go b/web/api/v1/json_codec.go index dfcdf78f8..f07e57696 100644 --- a/web/api/v1/json_codec.go +++ b/web/api/v1/json_codec.go @@ -241,8 +241,11 @@ func labelsIsEmpty(ptr unsafe.Pointer) bool { func unsafeMarshalVectorJSON(ptr unsafe.Pointer, stream *jsoniter.Stream) { v := *((*promql.Vector)(ptr)) stream.WriteArrayStart() - for _, s := range v { + for i, s := range v { marshalSampleJSON(s, stream) + if i != len(v)-1 { + stream.WriteMore() + } } stream.WriteArrayEnd() } @@ -251,8 +254,11 @@ func unsafeMarshalVectorJSON(ptr unsafe.Pointer, stream *jsoniter.Stream) { func unsafeMarshalMatrixJSON(ptr unsafe.Pointer, stream *jsoniter.Stream) { m := *((*promql.Matrix)(ptr)) stream.WriteArrayStart() - for _, s := range m { + for i, s := range m { marshalSeriesJSON(s, stream) + if i != len(m)-1 { + stream.WriteMore() + } } stream.WriteArrayEnd() } diff --git a/web/api/v1/json_codec_test.go b/web/api/v1/json_codec_test.go index b8384baaa..759dabd28 100644 --- a/web/api/v1/json_codec_test.go +++ b/web/api/v1/json_codec_test.go @@ -29,6 +29,40 @@ func TestJsonCodec_Encode(t *testing.T) { response interface{} expected string }{ + { + response: &QueryData{ + ResultType: parser.ValueTypeVector, + Result: promql.Vector{ + promql.Sample{ + Metric: labels.FromStrings("__name__", "foo"), + T: 1000, + F: 1, + }, + promql.Sample{ + Metric: labels.FromStrings("__name__", "bar"), + T: 2000, + F: 2, + }, + }, + }, + expected: `{"status":"success","data":{"resultType":"vector","result":[{"metric":{"__name__":"foo"},"value":[1,"1"]},{"metric":{"__name__":"bar"},"value":[2,"2"]}]}}`, + }, + { + response: &QueryData{ + ResultType: parser.ValueTypeMatrix, + Result: promql.Matrix{ + promql.Series{ + Metric: labels.FromStrings("__name__", "foo"), + Floats: []promql.FPoint{{F: 1, T: 1000}}, + }, + promql.Series{ + Metric: labels.FromStrings("__name__", "bar"), + Floats: []promql.FPoint{{F: 2, T: 2000}}, + }, + }, + }, + expected: `{"status":"success","data":{"resultType":"matrix","result":[{"metric":{"__name__":"foo"},"values":[[1,"1"]]},{"metric":{"__name__":"bar"},"values":[[2,"2"]]}]}}`, + }, { response: &QueryData{ ResultType: parser.ValueTypeMatrix,