Module: Matchers::JSON::JSONPath
- Included in:
- DocumentContainsJSONPath, JSONPathHasArray, JSONPathHasObject, JSONPathHasValue
- Defined in:
- lib/matchers/json/json_path.rb
Instance Method Summary collapse
-
#json_path_valid?(path) ⇒ Boolean
TODO: the regular expressions below will catch very few errors.
- #value_on_path(json_hash, path) ⇒ Object
Instance Method Details
#json_path_valid?(path) ⇒ Boolean
TODO: the regular expressions below will catch very few errors
29 30 31 32 33 34 |
# File 'lib/matchers/json/json_path.rb', line 29 def json_path_valid?(path) notation = path.include?('[\'') ? :bracket : :dot path_regex = /^\$[a-zA-Z0-9_(\[\d\])\.]*[^\.]$/ if notation == :dot path_regex = /^\$[a-zA-Z0-9_(\[\d\])\.\']*[^\.]$/ if notation == :bracket path_regex.match(path) end |
#value_on_path(json_hash, path) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/matchers/json/json_path.rb', line 13 def value_on_path(json_hash, path) raise ArgumentError, "Invalid json path: #{path}" unless json_path_valid?(path) path = translate_to_dot_notation(path) current_node = json_hash # start traversal at document root path_items(path).each do |path_item| element, index = decompose_path_item(path_item) begin current_node = fetch(current_node, element, index) rescue IndexError return nil end end current_node end |