jsonpath_eval.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2021 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package conf
  15. import (
  16. "context"
  17. "encoding/json"
  18. "fmt"
  19. "github.com/PaesslerAG/gval"
  20. "github.com/PaesslerAG/jsonpath"
  21. "github.com/lf-edge/ekuiper/pkg/cast"
  22. "reflect"
  23. )
  24. var builder = gval.Full(jsonpath.PlaceholderExtension())
  25. type JsonPathEval interface {
  26. Eval(data interface{}) (interface{}, error)
  27. }
  28. type gvalPathEval struct {
  29. valuer gval.Evaluable
  30. }
  31. func (e *gvalPathEval) Eval(data interface{}) (interface{}, error) {
  32. var input interface{}
  33. at := reflect.TypeOf(data)
  34. if at != nil {
  35. switch at.Kind() {
  36. case reflect.Map:
  37. input = cast.ConvertToInterfaceArr(data.(map[string]interface{}))
  38. case reflect.Slice:
  39. input = cast.ConvertSlice(data)
  40. case reflect.String:
  41. v, _ := data.(string)
  42. err := json.Unmarshal([]byte(v), &input)
  43. if err != nil {
  44. return nil, fmt.Errorf("data '%v' is not a valid json string", data)
  45. }
  46. default:
  47. return nil, fmt.Errorf("invalid data %v for jsonpath", data)
  48. }
  49. } else {
  50. return nil, fmt.Errorf("invalid data nil for jsonpath")
  51. }
  52. return e.valuer(context.Background(), input)
  53. }
  54. func GetJsonPathEval(jsonpath string) (JsonPathEval, error) {
  55. e, err := builder.NewEvaluable(jsonpath)
  56. if err != nil {
  57. return nil, err
  58. }
  59. return &gvalPathEval{valuer: e}, nil
  60. }