crowdsec/pkg/exprhelpers/jsonextract.go

61 lines
1.3 KiB
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 JsonExtractUnescape(jsblob string, target ...string) string {
value, err := jsonparser.GetString(
jsonparser.StringToBytes(jsblob),
target...,
)
if err != nil {
if err == jsonparser.KeyPathNotFoundError {
log.Debugf("%+v doesn't exist", target)
return ""
}
log.Errorf("JsonExtractUnescape : %+v : %s", target, err)
return ""
}
log.Tracef("extract path %+v", target)
strvalue := string(value)
return strvalue
}
2020-05-22 16:12:33 +00:00
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...)
}