Skip to content

Commit a184e7d

Browse files
committed
Enable numeric string key parsing in a path
1 parent 00cdf32 commit a184e7d

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

lib/json_spec/helpers.rb

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -34,18 +34,19 @@ def load_json(relative_path)
3434
def value_at_json_path(ruby, path)
3535
return ruby unless path
3636

37-
json_path_to_keys(path).inject(ruby) do |value, key|
37+
path.split("/").inject(ruby) do |value, key|
3838
case value
39-
when Hash, Array then value.fetch(key){ missing_json_path!(path) }
40-
else missing_json_path!(path)
39+
when Hash
40+
value.fetch(key){ missing_json_path!(path) }
41+
when Array
42+
missing_json_path!(path) unless key =~ /^\d+$/
43+
value.fetch(key.to_i){ missing_json_path!(path) }
44+
else
45+
missing_json_path!(path)
4146
end
4247
end
4348
end
4449

45-
def json_path_to_keys(path)
46-
path.split("/").map{|k| k =~ /^\d+$/ ? k.to_i : k }
47-
end
48-
4950
def missing_json_path!(path)
5051
raise JsonSpec::MissingPath.new(path)
5152
end

spec/json_spec/helpers_spec.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@
2828
expect{ parse_json(json, path) }.to raise_error(JsonSpec::MissingPath)
2929
end
3030
end
31+
32+
it "parses at a numeric string path" do
33+
json = %({"1":"two"})
34+
parse_json(%({"1":"two"}), "1").should == "two"
35+
end
3136
end
3237

3338
context "normalize_json" do

0 commit comments

Comments
 (0)