通过忽略 cucumber 中的顺序断言两个 json 内容
Assert two json content by ignoring the order in cucumber
我正在像这样比较 ruby+cucumber 中的两个 json 内容或对象
但是当我比较时,如果内容不同,它不会忽略内容的顺序。我知道这个语句比较两个字符串。那么无论如何我可以通过忽略其顺序来比较两个 json 对象吗?
expect(@act_resp_excl_key).to eq(exp_data_excl_key)
添加更多有关上述详细信息的信息。我有两个 json 文档,如下所示。
json1 = {
"entries" = > [{
"doingBusinessAsName" = > "KROGER FOODS",
"legalName" = > "Kroger-Corps"
}
]
}
json2 = {
"entries" = > [{
"legalName" = > "Kroger-Corps"
"doingBusinessAsName" = > "KROGER FOODS",
}
]
}
当我比较 ruby+cucumber 中的这两个 json 时,我得到的结果是失败。但从逻辑上讲它是一样的,我应该通过。我用上面的比较语句来验证两个jsons.
@tgf,
我使用了您指定的语句,但我的比较仍然失败。你能帮我看看是什么问题吗?
expect(JSON.parse(@act_resp_excl_key)).to eq JSON.parse(exp_data_excl_key)
如果数据只是 JSON 字符串(请 post 数据示例),您可以将其解析为 ruby 散列并进行比较。
require 'json'
JSON.parse(@act_resp_excl_key).class => Hash
然后断言两个哈希值相等:
expect(JSON.parse(@act_resp_excl_key)).to eq JSON.parse(exp_data_excl_key)
即使顺序不同也能正常工作。
对于 json2,您的逗号位置不正确。
> json1 = { "entries" => [{ "doingBusinessAsName" => "KROGER FOODS", "legalName" => "Kroger-Corps" } ] }
=> {"entries"=>[{"doingBusinessAsName"=>"KROGER FOODS", "legalName"=>"Kroger-Corps"}]}
> json2 = { "entries" => [{ "legalName" => "Kroger-Corps", "doingBusinessAsName" => "KROGER FOODS" } ] }
=> {"entries"=>[{"legalName"=>"Kroger-Corps", "doingBusinessAsName"=>"KROGER FOODS"}]}
> json1==json2
=> true
我正在像这样比较 ruby+cucumber 中的两个 json 内容或对象 但是当我比较时,如果内容不同,它不会忽略内容的顺序。我知道这个语句比较两个字符串。那么无论如何我可以通过忽略其顺序来比较两个 json 对象吗?
expect(@act_resp_excl_key).to eq(exp_data_excl_key)
添加更多有关上述详细信息的信息。我有两个 json 文档,如下所示。
json1 = {
"entries" = > [{
"doingBusinessAsName" = > "KROGER FOODS",
"legalName" = > "Kroger-Corps"
}
]
}
json2 = {
"entries" = > [{
"legalName" = > "Kroger-Corps"
"doingBusinessAsName" = > "KROGER FOODS",
}
]
}
当我比较 ruby+cucumber 中的这两个 json 时,我得到的结果是失败。但从逻辑上讲它是一样的,我应该通过。我用上面的比较语句来验证两个jsons.
@tgf, 我使用了您指定的语句,但我的比较仍然失败。你能帮我看看是什么问题吗?
expect(JSON.parse(@act_resp_excl_key)).to eq JSON.parse(exp_data_excl_key)
如果数据只是 JSON 字符串(请 post 数据示例),您可以将其解析为 ruby 散列并进行比较。
require 'json'
JSON.parse(@act_resp_excl_key).class => Hash
然后断言两个哈希值相等:
expect(JSON.parse(@act_resp_excl_key)).to eq JSON.parse(exp_data_excl_key)
即使顺序不同也能正常工作。
对于 json2,您的逗号位置不正确。
> json1 = { "entries" => [{ "doingBusinessAsName" => "KROGER FOODS", "legalName" => "Kroger-Corps" } ] }
=> {"entries"=>[{"doingBusinessAsName"=>"KROGER FOODS", "legalName"=>"Kroger-Corps"}]}
> json2 = { "entries" => [{ "legalName" => "Kroger-Corps", "doingBusinessAsName" => "KROGER FOODS" } ] }
=> {"entries"=>[{"legalName"=>"Kroger-Corps", "doingBusinessAsName"=>"KROGER FOODS"}]}
> json1==json2
=> true