From 47b2d04d5b753ccc08e1d17300e4f9d3120b59e6 Mon Sep 17 00:00:00 2001 From: Daniel Nelson Date: Tue, 26 Sep 2017 15:58:33 -0700 Subject: [PATCH] Allow JSON data format to contain zero metrics (#3268) (cherry picked from commit 22a9ffbb9d9b29754aa8f3a38c86ece64d95a9be) --- plugins/inputs/httpjson/httpjson_test.go | 6 ++---- plugins/parsers/json/parser.go | 4 ++++ plugins/parsers/json/parser_test.go | 10 ++++++++++ 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/plugins/inputs/httpjson/httpjson_test.go b/plugins/inputs/httpjson/httpjson_test.go index 60ee88b49..7134ffb46 100644 --- a/plugins/inputs/httpjson/httpjson_test.go +++ b/plugins/inputs/httpjson/httpjson_test.go @@ -477,15 +477,13 @@ func TestHttpJsonBadJson(t *testing.T) { assert.Equal(t, 0, acc.NFields()) } -// Test response to empty string as response objectgT +// Test response to empty string as response object func TestHttpJsonEmptyResponse(t *testing.T) { httpjson := genMockHttpJson(empty, 200) var acc testutil.Accumulator err := acc.GatherError(httpjson[0].Gather) - - assert.Error(t, err) - assert.Equal(t, 0, acc.NFields()) + assert.NoError(t, err) } // Test that the proper values are ignored or collected diff --git a/plugins/parsers/json/parser.go b/plugins/parsers/json/parser.go index a8743558d..50b3d3682 100644 --- a/plugins/parsers/json/parser.go +++ b/plugins/parsers/json/parser.go @@ -67,6 +67,10 @@ func (p *JSONParser) parseObject(metrics []telegraf.Metric, jsonOut map[string]i } func (p *JSONParser) Parse(buf []byte) ([]telegraf.Metric, error) { + buf = bytes.TrimSpace(buf) + if len(buf) == 0 { + return make([]telegraf.Metric, 0), nil + } if !isarray(buf) { metrics := make([]telegraf.Metric, 0) diff --git a/plugins/parsers/json/parser_test.go b/plugins/parsers/json/parser_test.go index c8e2be1ad..f21961787 100644 --- a/plugins/parsers/json/parser_test.go +++ b/plugins/parsers/json/parser_test.go @@ -84,6 +84,16 @@ func TestParseValidJSON(t *testing.T) { "b_c": float64(6), }, metrics[0].Fields()) assert.Equal(t, map[string]string{}, metrics[0].Tags()) + + // Test that whitespace only will parse as an empty list of metrics + metrics, err = parser.Parse([]byte("\n\t")) + assert.NoError(t, err) + assert.Len(t, metrics, 0) + + // Test that an empty string will parse as an empty list of metrics + metrics, err = parser.Parse([]byte("")) + assert.NoError(t, err) + assert.Len(t, metrics, 0) } func TestParseLineValidJSON(t *testing.T) {