Class: JSONP3::JSONPath

Inherits:
Object
  • Object
show all
Defined in:
lib/json_p3/path.rb

Overview

A compiled JSONPath expression ready to be applied to JSON-like values.

Instance Method Summary collapse

Constructor Details

#initialize(env, segments) ⇒ JSONPath

Returns a new instance of JSONPath.



8
9
10
11
# File 'lib/json_p3/path.rb', line 8

def initialize(env, segments)
  @env = env
  @segments = segments
end

Instance Method Details

#empty?Boolean

Return true if this JSONPath expression has no segments.

Returns:

  • (Boolean)


38
39
40
# File 'lib/json_p3/path.rb', line 38

def empty?
  @segments.empty?
end

#find(root) ⇒ Array<JSONPathNode> Also known as: apply

Apply this JSONPath expression to JSON-like value root.

Parameters:

  • root (Array, Hash, String, Integer, nil)

    the root JSON-like value to apply this query to.

Returns:

  • (Array<JSONPathNode>)

    the sequence of nodes found while applying this query to root.



20
21
22
23
24
# File 'lib/json_p3/path.rb', line 20

def find(root)
  nodes = [JSONPathNode.new(root, [], root)]
  @segments.each { |segment| nodes = segment.resolve(nodes) }
  JSONPathNodeList.new(nodes)
end

#singular?Boolean

Return true if this JSONPath expression is a singular query.

Returns:

  • (Boolean)


29
30
31
32
33
34
35
# File 'lib/json_p3/path.rb', line 29

def singular?
  @segments.each do |segment|
    return false if segment.instance_of? RecursiveDescentSegment
    return false unless segment.selectors.length == 1 && segment.selectors[0].singular?
  end
  true
end

#to_sObject



13
14
15
# File 'lib/json_p3/path.rb', line 13

def to_s
  "$#{@segments.map(&:to_s).join}"
end