...

Source file src/github.com/exponent-io/jsonpath/path.go

Documentation: github.com/exponent-io/jsonpath

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

View as plain text