Class: JsonPath

Inherits:
Object
  • Object
show all
Defined in:
lib/jsonpath.rb,
lib/jsonpath/proxy.rb,
lib/jsonpath/version.rb,
lib/jsonpath/enumerable.rb

Defined Under Namespace

Classes: Enumerable, Proxy

Constant Summary collapse

PATH_ALL =
'$..*'
VERSION =
'0.5.2'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, opts = nil) ⇒ JsonPath

Returns a new instance of JsonPath.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/jsonpath.rb', line 13

def initialize(path, opts = nil)
  @opts = opts
  scanner = StringScanner.new(path)
  @path = []
  bracket_count = 0
  while not scanner.eos?
    if token = scanner.scan(/\$/)
      @path << token
    elsif token = scanner.scan(/@/)
      @path << token
    elsif token = scanner.scan(/[a-zA-Z0-9_-]+/)
      @path << "['#{token}']"
    elsif token = scanner.scan(/'(.*?)'/)
      @path << "[#{token}]"
    elsif token = scanner.scan(/\[/)
      count = 1
      while !count.zero?
        if t = scanner.scan(/\[/)
          token << t
          count += 1
        elsif t = scanner.scan(/\]/)
          token << t
          count -= 1
        elsif t = scanner.scan(/[^\[\]]*/)
          token << t
        end
      end
      @path << token
    elsif token = scanner.scan(/\.\./)
      @path << token
    elsif scanner.scan(/\./)
      nil
    elsif token = scanner.scan(/\*/)
      @path << token
    elsif token = scanner.scan(/[><=] \d+/)
      @path.last << token
    elsif token = scanner.scan(/./)
      @path.last << token
    end
  end
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



11
12
13
# File 'lib/jsonpath.rb', line 11

def path
  @path
end

Class Method Details

.for(obj_or_str) ⇒ Object



72
73
74
# File 'lib/jsonpath.rb', line 72

def self.for(obj_or_str)
  Proxy.new(process_object(obj_or_str))
end

.on(obj_or_str, path, opts = nil) ⇒ Object



68
69
70
# File 'lib/jsonpath.rb', line 68

def self.on(obj_or_str, path, opts = nil)
  self.new(path, opts).on(process_object(obj_or_str))
end

Instance Method Details

#enum_on(obj_or_str, mode = nil) ⇒ Object Also known as: []



63
64
65
# File 'lib/jsonpath.rb', line 63

def enum_on(obj_or_str, mode = nil)
  JsonPath::Enumerable.new(self, self.class.process_object(obj_or_str), mode, @opts)
end

#first(obj_or_str, *args) ⇒ Object



59
60
61
# File 'lib/jsonpath.rb', line 59

def first(obj_or_str, *args)
  enum_on(obj_or_str).first(*args)
end

#on(obj_or_str) ⇒ Object



55
56
57
# File 'lib/jsonpath.rb', line 55

def on(obj_or_str)
  enum_on(obj_or_str).to_a
end