path.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Extends the Go runtime's json.Decoder enabling navigation of a stream of json tokens.
  2. package jsonpath
  3. import "fmt"
  4. type jsonContext int
  5. const (
  6. none jsonContext = iota
  7. objKey
  8. objValue
  9. arrValue
  10. )
  11. // AnyIndex can be used in a pattern to match any array index.
  12. const AnyIndex = -2
  13. // JsonPath is a slice of strings and/or integers. Each string specifies an JSON object key, and
  14. // each integer specifies an index into a JSON array.
  15. type JsonPath []interface{}
  16. func (p *JsonPath) push(n interface{}) { *p = append(*p, n) }
  17. func (p *JsonPath) pop() { *p = (*p)[:len(*p)-1] }
  18. // increment the index at the top of the stack (must be an array index)
  19. func (p *JsonPath) incTop() { (*p)[len(*p)-1] = (*p)[len(*p)-1].(int) + 1 }
  20. // name the key at the top of the stack (must be an object key)
  21. func (p *JsonPath) nameTop(n string) { (*p)[len(*p)-1] = n }
  22. // infer the context from the item at the top of the stack
  23. func (p *JsonPath) inferContext() jsonContext {
  24. if len(*p) == 0 {
  25. return none
  26. }
  27. t := (*p)[len(*p)-1]
  28. switch t.(type) {
  29. case string:
  30. return objKey
  31. case int:
  32. return arrValue
  33. default:
  34. panic(fmt.Sprintf("Invalid stack type %T", t))
  35. }
  36. }
  37. // Equal tests for equality between two JsonPath types.
  38. func (p *JsonPath) Equal(o JsonPath) bool {
  39. if len(*p) != len(o) {
  40. return false
  41. }
  42. for i, v := range *p {
  43. if v != o[i] {
  44. return false
  45. }
  46. }
  47. return true
  48. }
  49. func (p *JsonPath) HasPrefix(o JsonPath) bool {
  50. for i, v := range o {
  51. if v != (*p)[i] {
  52. return false
  53. }
  54. }
  55. return true
  56. }