crowdsec/pkg/exprhelpers/jsonextract.go

42 lines
881 B
Go
Raw Normal View History

2020-05-22 16:12:33 +00:00
package exprhelpers
import (
"strings"
"github.com/buger/jsonparser"
log "github.com/sirupsen/logrus"
)
func JsonExtractLib(jsblob string, target ...string) string {
value, dataType, _, err := jsonparser.Get(
jsonparser.StringToBytes(jsblob),
target...,
)
2020-05-22 16:12:33 +00:00
if err != nil {
if err == jsonparser.KeyPathNotFoundError {
log.Debugf("%+v doesn't exist", target)
return ""
}
2020-05-23 11:22:43 +00:00
log.Errorf("jsonExtractLib : %+v : %s", target, err)
2020-05-22 16:12:33 +00:00
return ""
}
if dataType == jsonparser.NotExist {
log.Debugf("%+v doesn't exist", target)
return ""
}
strvalue := string(value)
return strvalue
}
func JsonExtract(jsblob string, target string) string {
2020-05-23 11:22:43 +00:00
if !strings.HasPrefix(target, "[") {
target = strings.Replace(target, "[", ".[", -1)
}
2020-05-22 16:12:33 +00:00
fullpath := strings.Split(target, ".")
2020-05-23 11:22:43 +00:00
log.Tracef("extract path %+v", fullpath)
2020-05-22 16:12:33 +00:00
return JsonExtractLib(jsblob, fullpath...)
}