api.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package jmespath
  2. import "strconv"
  3. // JMESPath is the epresentation of a compiled JMES path query. A JMESPath is
  4. // safe for concurrent use by multiple goroutines.
  5. type JMESPath struct {
  6. ast ASTNode
  7. intr *treeInterpreter
  8. }
  9. // Compile parses a JMESPath expression and returns, if successful, a JMESPath
  10. // object that can be used to match against data.
  11. func Compile(expression string) (*JMESPath, error) {
  12. parser := NewParser()
  13. ast, err := parser.Parse(expression)
  14. if err != nil {
  15. return nil, err
  16. }
  17. jmespath := &JMESPath{ast: ast, intr: newInterpreter()}
  18. return jmespath, nil
  19. }
  20. // MustCompile is like Compile but panics if the expression cannot be parsed.
  21. // It simplifies safe initialization of global variables holding compiled
  22. // JMESPaths.
  23. func MustCompile(expression string) *JMESPath {
  24. jmespath, err := Compile(expression)
  25. if err != nil {
  26. panic(`jmespath: Compile(` + strconv.Quote(expression) + `): ` + err.Error())
  27. }
  28. return jmespath
  29. }
  30. // Search evaluates a JMESPath expression against input data and returns the result.
  31. func (jp *JMESPath) Search(data interface{}) (interface{}, error) {
  32. return jp.intr.Execute(jp.ast, data)
  33. }
  34. // Search evaluates a JMESPath expression against input data and returns the result.
  35. func Search(expression string, data interface{}) (interface{}, error) {
  36. intr := newInterpreter()
  37. parser := NewParser()
  38. ast, err := parser.Parse(expression)
  39. if err != nil {
  40. return nil, err
  41. }
  42. return intr.Execute(ast, data)
  43. }