有什么好方法可以检查一个json对象是否是Ruby中另一个json对象的子集?
我的意思是,a是b的json子集有什么好方法可以检查一个json对象是否是Ruby中另一个json对象的子集?,ruby,json,Ruby,Json,我的意思是,a是b的json子集 对于对象,b具有a中的所有键值对 对于数组,b的大小与a相同,但顺序并不重要 {"one":1}.should be_subset_json({"one":1,"two":2}) [{"one":1}].should_NOT be_subset_json([{"one":1},{"two":2}]) [{"two":2},{"one":1}].should be_subset_json([{"one":1},{"two":2}]) [{"id":1},{"id
- 对于对象,b具有a中的所有键值对
- 对于数组,b的大小与a相同,但顺序并不重要
{"one":1}.should be_subset_json({"one":1,"two":2}) [{"one":1}].should_NOT be_subset_json([{"one":1},{"two":2}]) [{"two":2},{"one":1}].should be_subset_json([{"one":1},{"two":2}]) [{"id":1},{"id":2}].should be_subset_json([{"id":2, "name":"b"},{"id":1,"name":"a"}])
require 'json'
def diff_structure(a, b)
case a
when Array
a.map(&:hash).sort == b.map(&:hash).sort
when Hash
a.all? {|k, v| diff_structure(v, b[k]) }
else
a == b
end
end
RSpec::Matchers.define :be_subset_json do |expected|
match do |actual|
diff_structure JSON.parse(actual), JSON.parse(expected)
end
end
describe "Data structure subsets" do
specify { '{"one":1}'.should be_subset_json('{"one":1,"two":2}') }
specify { '[{"one":1}]'.should_not be_subset_json('[{"one":1},{"two":2}]') }
specify { '[{"two":2},{"one":1}]'.should be_subset_json('[{"one":1},{"two":2}]') }
specify { '{"a":{"one":1}}'.should be_subset_json('{"a":{"one":1,"two":2}}') }
end
# Data structure subsets
# should be subset json "{\"one\":1,\"two\":2}"
# should not be subset json "[{\"one\":1},{\"two\":2}]"
# should be subset json "[{\"one\":1},{\"two\":2}]"
# should be subset json "{\"a\":{\"one\":1,\"two\":2}}"
# Finished in 0.00172 seconds
# 4 examples, 0 failures
JSON?或者常规的ruby数组和散列?啊,我以JSON.parse为例。为什么这一行
a.map(&:hash)。sort==b.map(&:hash)。sort
?因为hash
不一定是可比的,但是我们可以通过(ab)使用Object\hash
来测试是否相等。试试[{two:2},{one:1}].排序
。我的意思是说检查大小(对于数组,b与a大小相同,但顺序并不重要),而不是内容。。所以我问你为什么写这样一个额外的逻辑?如果他真的只是想测试大小,那么是的,这是多余的。不过,[1]
成为[“argleblagle”]
的子集似乎很愚蠢。