From f21f31a08ab8eba4f98cb55d2390db44476e5f33 Mon Sep 17 00:00:00 2001 From: Daniel Meiners Date: Thu, 3 May 2018 20:40:28 +0200 Subject: [PATCH] Ignore UTF8 BOM in JSON parser (#4099) (cherry picked from commit 9647ea88eafab45063909825e1a491d509b0e3b8) --- plugins/parsers/json/parser.go | 5 +++++ plugins/parsers/json/parser_test.go | 12 ++++++++++++ 2 files changed, 17 insertions(+) diff --git a/plugins/parsers/json/parser.go b/plugins/parsers/json/parser.go index ecf9996af..8a3d15be7 100644 --- a/plugins/parsers/json/parser.go +++ b/plugins/parsers/json/parser.go @@ -12,6 +12,10 @@ import ( "github.com/influxdata/telegraf/metric" ) +var ( + utf8BOM = []byte("\xef\xbb\xbf") +) + type JSONParser struct { MetricName string TagKeys []string @@ -68,6 +72,7 @@ func (p *JSONParser) parseObject(metrics []telegraf.Metric, jsonOut map[string]i func (p *JSONParser) Parse(buf []byte) ([]telegraf.Metric, error) { buf = bytes.TrimSpace(buf) + buf = bytes.TrimPrefix(buf, utf8BOM) if len(buf) == 0 { return make([]telegraf.Metric, 0), nil } diff --git a/plugins/parsers/json/parser_test.go b/plugins/parsers/json/parser_test.go index f21961787..c4f946364 100644 --- a/plugins/parsers/json/parser_test.go +++ b/plugins/parsers/json/parser_test.go @@ -428,3 +428,15 @@ func TestParseArrayWithTagKeys(t *testing.T) { "othertag": "baz", }, metrics[1].Tags()) } + +var jsonBOM = []byte("\xef\xbb\xbf[{\"value\":17}]") + +func TestHttpJsonBOM(t *testing.T) { + parser := JSONParser{ + MetricName: "json_test", + } + + // Most basic vanilla test + _, err := parser.Parse(jsonBOM) + assert.NoError(t, err) +}