我有以下json响应,这里I1是主要对象而I1-1,I1-2是子对象
{
"I1": "Main Object 1",
"I1-1": "Sub Object 1",
"I1-2": "Sub Object 2",
"I2": "Main Object 2",
"I2-1": "Sub Object 1",
"I2-2": "Sub Object 2",
"I3": "Main Object 3",
"I3-1": "Sub Object 1",
"I3-2": "Sub Object 2"
}
如何解析上面的响应以过滤ruby中的main_objects和sub_objects?
答案 0 :(得分:0)
require 'json'
data = JSON.parse('{
"I1": "Main Object 1",
"I1-1": "Sub Object 1",
"I1-2": "Sub Object 2",
"I2": "Main Object 2",
"I2-1": "Sub Object 1",
"I2-2": "Sub Object 2",
"I3": "Main Object 3",
"I3-1": "Sub Object 1",
"I3-2": "Sub Object 2"
}')
main_objects = data.select { |k, _| k =~ /\AI\d+\z/ }
sub_objects = data.select { |k, _| k =~ /\AI\d+\-\d+\z/ }
p main_objects # => {"I1"=>"Main Object 1", "I2"=>"Main Object 2", "I3"=>"Main Object 3"}
p sub_objects # => {"I1-1"=>"Sub Object 1", "I1-2"=>"Sub Object 2", "I2-1"=>"Sub Object 1", "I2-2"=>"Sub Object 2", "I3-1"=>"Sub Object 1", "I3-2"=>"Sub Object 2"}