add option to mark field as int

This commit is contained in:
Max U
2018-07-02 11:20:16 -07:00
parent 92e156c784
commit d4a4ac25bb
4 changed files with 74 additions and 13 deletions

View File

@@ -13,24 +13,34 @@ type JSONPath struct {
MetricName string
TagPath map[string]string
FloatPath map[string]string
IntPath map[string]string
StrPath map[string]string
BoolPath map[string]string
DefaultTags map[string]string
}
func (j *JSONPath) Parse(buf []byte) ([]telegraf.Metric, error) {
tags := j.DefaultTags
tags := make(map[string]string)
for k, v := range j.DefaultTags {
tags[k] = v
}
fields := make(map[string]interface{})
metrics := make([]telegraf.Metric, 0)
for k, v := range j.TagPath {
c := gjson.GetBytes(buf, v)
tags[k] = c.Str
tags[k] = c.String()
}
for k, v := range j.FloatPath {
c := gjson.GetBytes(buf, v)
fields[k] = c.Num
fields[k] = c.Float()
}
for k, v := range j.IntPath {
c := gjson.GetBytes(buf, v)
fields[k] = c.Int()
log.Printf("got a int: fields[%v]: %v", k, c.Int())
}
for k, v := range j.BoolPath {
@@ -46,7 +56,7 @@ func (j *JSONPath) Parse(buf []byte) ([]telegraf.Metric, error) {
for k, v := range j.StrPath {
c := gjson.GetBytes(buf, v)
fields[k] = c.Str
fields[k] = c.String()
}
m, err := metric.New(j.MetricName, tags, fields, time.Now())

View File

@@ -2,6 +2,7 @@ package gjson
import (
"log"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
@@ -38,3 +39,35 @@ func TestParseJsonPath(t *testing.T) {
t.Error()
}
func TestTagTypes(t *testing.T) {
testString := `{
"total_devices": 5,
"total_threads": 10,
"shares": {
"total": 5,
"accepted": 5,
"rejected": 0,
"my_bool": true,
"tester": "work",
"tester2": {
"hello":"sup",
"fun":true,
"break":9.97
}
}
}`
r := JSONPath{
TagPath: map[string]string{"int1": "total_devices", "my_bool": "shares.my_bool"},
FloatPath: map[string]string{"total": "shares.total"},
BoolPath: map[string]string{"fun": "shares.tester2.fun"},
StrPath: map[string]string{"hello": "shares.tester2.hello"},
IntPath: map[string]string{"accepted": "shares.accepted"},
}
metrics, err := r.Parse([]byte(testString))
log.Printf("m[0] name: %v, tags: %v, fields: %v", metrics[0].Name(), metrics[0].Tags(), metrics[0].Fields())
assert.NoError(t, err)
assert.Equal(t, true, reflect.DeepEqual(map[string]interface{}{"total": 5.0, "fun": true, "hello": "sup", "accepted": int64(5)}, metrics[0].Fields()))
}