解析复杂的哈希并返回对键的更改

时间:2018-11-17 06:51:48

标签: ruby-on-rails json ruby hash

我正在使用json-compare gem比较两个不同的json文件。

示例文件1:

{"suggestions": [
      {
        "id1": 1,
        "title1": "Test",
        "body1": "Test"
       }
    ]
}

示例文件2:

{"suggestions": [
      {
        "id2": 1,
        "title2": "Test",
        "body2": "Test"
      }
    ]
}

该宝石运行良好,并散发出如下哈希:

  {:update=> 
    {"suggestions" => 
        {:update=>
          {0=>
            {:append=>
                {"id2"=>1, "title2"=>"Test", "body2"=>"Test"}, 
             :remove=>
                {"id1"=>1, "title1"=>"Test", "body1"=>"Test"}, 
             }
          }
        }
    }
}

我该如何解析并返回所有更改JSON Key的地方?为了简单起见,我将如何放置到控制台:

id1 changed to id2
title1 changed to title2
body1 changed to body2

出于我要构建的目的,我不需要知道对值的更改。我只需要知道id1变成id2,等等。

2 个答案:

答案 0 :(得分:1)

除非您要继续进行键排序,否则无法告诉id1id2取代,title2title1取代,或者{{1} }成为id1,而title1成为id2。听起来您需要与实际键名相关的特定逻辑(在此示例中,搜索不同的整数后缀)。

答案 1 :(得分:0)

也许这足以满足目的:

def find_what_changed_in(mhash, result = [])
  result << mhash
  return if mhash.keys == [:append, :remove]
  mhash.keys.each { |k| find_what_changed_in(mhash[k], result) }
  result.last
end

find_what_changed_in(changes)

#=> {:append=>{"id2"=>1, "title2"=>"Test", "body2"=>"Test"}, :remove=>{"id1"=>1, "title1"=>"Test", "body1"=>"Test"}}

位置:

changes =   {:update=> 
    {"suggestions" => 
        {:update=>
          {0=>
            {:append=>
                {"id2"=>1, "title2"=>"Test", "body2"=>"Test"}, 
             :remove=>
                {"id1"=>1, "title1"=>"Test", "body1"=>"Test"}, 
...
相关问题