Handle more complex array in json path

Signed-off-by: Mikkel Oscar Lyderik Larsen <mikkel.larsen@zalando.de>
This commit is contained in:
Mikkel Oscar Lyderik Larsen 2021-10-14 09:34:15 +02:00
parent e04cd10bfc
commit 4acdf72ef7
No known key found for this signature in database
GPG Key ID: 50AD98B2A0D8D4EF
2 changed files with 23 additions and 1 deletions

View File

@ -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 {

View File

@ -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}`),