Class: JsonPath

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

Constant Summary collapse

DEBUG =
false

Class Method Summary collapse

Class Method Details

.convert_to_re(pattern) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/json_path.rb', line 10

def self.convert_to_re(pattern)
  re = pattern.dup
  re = re.gsub('[', '\[').gsub(']', '\]')# escape brackets
  re.gsub!(/^\$/, '^\$') # escape $ and fix it to root
  re.gsub!('.', '\.') # escape dots
  re.gsub!(/ \\\[  \*  \\\] /x, '\[\d+\]') # change [*] to [\d+]
  re.gsub!('\.\.', '(?<=[\.\$\]]).*[\.\]]') # change .. to match a dot, $, or ] followed by anything, and ending in a . or ]
  re.gsub!('\.*', '\.[^\.\[\]]+') # wild card will match any key
  
  re += '(?=$)' #'(?=$|\.)
  puts "#{pattern}\t=>\t#{re}" if DEBUG
  Regexp.new(re)
end

.matches?(path, pattern) ⇒ Boolean

Returns:

  • (Boolean)


4
5
6
7
# File 'lib/json_path.rb', line 4

def self.matches?(path, pattern)
  re = self.convert_to_re(pattern)
  !path.match(re).nil?
end