Class: JsonPaths
- Inherits:
-
Object
- Object
- JsonPaths
- Includes:
- Enumerable
- Defined in:
- lib/json_paths.rb,
lib/json_paths/version.rb
Constant Summary collapse
- VERSION =
"0.0.5"
Instance Attribute Summary collapse
-
#json ⇒ Object
readonly
Returns the value of attribute json.
-
#paths ⇒ Object
readonly
Returns the value of attribute paths.
Instance Method Summary collapse
- #each ⇒ Object
-
#initialize(json) ⇒ JsonPaths
constructor
A new instance of JsonPaths.
- #json_to_paths ⇒ Object
- #key_to_path(hash, key) ⇒ Object
Constructor Details
#initialize(json) ⇒ JsonPaths
Returns a new instance of JsonPaths.
10 11 12 13 14 |
# File 'lib/json_paths.rb', line 10 def initialize(json) @json = json @paths = json_to_paths end |
Instance Attribute Details
#json ⇒ Object (readonly)
Returns the value of attribute json.
7 8 9 |
# File 'lib/json_paths.rb', line 7 def json @json end |
#paths ⇒ Object (readonly)
Returns the value of attribute paths.
8 9 10 |
# File 'lib/json_paths.rb', line 8 def paths @paths end |
Instance Method Details
#each ⇒ Object
16 17 18 |
# File 'lib/json_paths.rb', line 16 def each paths.each end |
#json_to_paths ⇒ Object
20 21 22 23 24 25 26 27 28 29 |
# File 'lib/json_paths.rb', line 20 def json_to_paths parsed_json = JSON.parse(json) paths = [] parsed_json.each_key do |key| paths << key_to_path(parsed_json, key) end paths.flatten.map { |path| "$." + path } end |
#key_to_path(hash, key) ⇒ Object
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/json_paths.rb', line 31 def key_to_path(hash, key) paths_for_key = [] value = hash[key] if value.respond_to?(:keys) value.each_key do |k| paths_for_key << key_to_path(value, k).map do |ktp| ktp = ktp.first unless ktp.is_a?(String) key + "." + ktp end end elsif value.respond_to?(:each_with_index) value.each_with_index do |v,i| paths_for_key << JsonPaths.new(v.to_json).paths.map do |j| "#{key}[#{i}].#{j.gsub('$.', '')}" end end else paths_for_key << key.to_s end paths_for_key end |