...

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

Documentation: github.com/exponent-io/jsonpath

     1  package jsonpath
     2  
     3  // pathNode is used to construct a trie of paths to be matched
     4  type pathNode struct {
     5  	matchOn    interface{} // string, or integer
     6  	childNodes []pathNode
     7  	action     DecodeAction
     8  }
     9  
    10  // match climbs the trie to find a node that matches the given JSON path.
    11  func (n *pathNode) match(path JsonPath) *pathNode {
    12  	var node *pathNode = n
    13  	for _, ps := range path {
    14  		found := false
    15  		for i, n := range node.childNodes {
    16  			if n.matchOn == ps {
    17  				node = &node.childNodes[i]
    18  				found = true
    19  				break
    20  			} else if _, ok := ps.(int); ok && n.matchOn == AnyIndex {
    21  				node = &node.childNodes[i]
    22  				found = true
    23  				break
    24  			}
    25  		}
    26  		if !found {
    27  			return nil
    28  		}
    29  	}
    30  	return node
    31  }
    32  
    33  // PathActions represents a collection of DecodeAction functions that should be called at certain path positions
    34  // when scanning the JSON stream. PathActions can be created once and used many times in one or more JSON streams.
    35  type PathActions struct {
    36  	node pathNode
    37  }
    38  
    39  // DecodeAction handlers are called by the Decoder when scanning objects. See PathActions.Add for more detail.
    40  type DecodeAction func(d *Decoder) error
    41  
    42  // Add specifies an action to call on the Decoder when the specified path is encountered.
    43  func (je *PathActions) Add(action DecodeAction, path ...interface{}) {
    44  
    45  	var node *pathNode = &je.node
    46  	for _, ps := range path {
    47  		found := false
    48  		for i, n := range node.childNodes {
    49  			if n.matchOn == ps {
    50  				node = &node.childNodes[i]
    51  				found = true
    52  				break
    53  			}
    54  		}
    55  		if !found {
    56  			node.childNodes = append(node.childNodes, pathNode{matchOn: ps})
    57  			node = &node.childNodes[len(node.childNodes)-1]
    58  		}
    59  	}
    60  	node.action = action
    61  }
    62  

View as plain text