Method: JsonQuery::Data.walk

Defined in:
lib/json_query/data.rb

.walk(data:, path:) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/json_query/data.rb', line 4

def self.walk(data:, path:)
  current = data
  path.each do |segment|
    results = segment.match(/^(.*)\[([0-9]+)\]$/)
    key, index = if results
      results.captures
    else
      [segment, nil]
    end
    if current.has_key?(key)
      current = current[key]
    else
      puts "Path #{path.join(".")} is not valid: the key `#{segment}` is not present."
      exit 1
    end
    if index
      index = index.to_i
      if is_list?(current) && current.count > index
        current = current[index]
      else
        puts "Path #{path.join(".")} is not valid: not a list of the index is out of bound."
        exit 1
      end
    end
  end
  current
end