From 4acdf72ef73a044c5527b484f95fda4664668b3d Mon Sep 17 00:00:00 2001 From: Mikkel Oscar Lyderik Larsen Date: Thu, 14 Oct 2021 09:34:15 +0200 Subject: [PATCH] Handle more complex array in json path Signed-off-by: Mikkel Oscar Lyderik Larsen --- pkg/collector/httpmetrics/json_path.go | 17 ++++++++++++++++- pkg/collector/httpmetrics/json_path_test.go | 7 +++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/pkg/collector/httpmetrics/json_path.go b/pkg/collector/httpmetrics/json_path.go index 871565f..a85b5e5 100644 --- a/pkg/collector/httpmetrics/json_path.go +++ b/pkg/collector/httpmetrics/json_path.go @@ -72,10 +72,25 @@ func (g *JSONPathMetricsGetter) GetMetric(metricsURL url.URL) (float64, error) { return 0, err } - if len(nodes) != 1 { + if len(nodes) == 0 { return 0, fmt.Errorf("unexpected json: expected single numeric or array value") } + if len(nodes) > 1 { + if g.aggregator == nil { + return 0, fmt.Errorf("no aggregator function has been specified") + } + values := make([]float64, 0, len(nodes)) + for _, node := range nodes { + v, err := node.GetNumeric() + if err != nil { + return 0, fmt.Errorf("unexpected json: did not find numeric or array value '%s': %w", nodes, err) + } + values = append(values, v) + } + return g.aggregator(values...), nil + } + node := nodes[0] if node.IsArray() { if g.aggregator == nil { diff --git a/pkg/collector/httpmetrics/json_path_test.go b/pkg/collector/httpmetrics/json_path_test.go index 716f283..b2150c3 100644 --- a/pkg/collector/httpmetrics/json_path_test.go +++ b/pkg/collector/httpmetrics/json_path_test.go @@ -51,6 +51,13 @@ func TestJSONPathMetricsGetter(t *testing.T) { result: 5, aggregator: Average, }, + { + name: "glob array query", + jsonResponse: []byte(`{"worker_status":[{"last_status":{"backlog":3}},{"last_status":{"backlog":7}}]}`), + jsonPath: "$.worker_status.[*].last_status.backlog", + result: 5, + aggregator: Average, + }, { name: "json path not resulting in array or number should lead to error", jsonResponse: []byte(`{"metric.value":5}`),