在 ruby​​ 中解析具有重复键的 json 字符串

use*_*116 1 ruby json

我有一个带有重复键的 json,如下所示:

{"a":{
"stateId":"b",
"countyId":["c"]
},"a":{
"stateId":"d",
"countyId":["e"]
}}
Run Code Online (Sandbox Code Playgroud)

当我使用JSON.parseor时JSON(stirng),它会解析并为我提供带有值的键d, e。我需要解析 json,这样它就可以避免解析相同的键两次,并且具有b, c该键的值'a'而不是'd', 'e'.

Jon*_*ger 7

有一种方法。不使用常用的 Hash 类来解析 JSON 对象,而是使用稍微修改过的类,它可以检查键是否已存在:

class DuplicateCheckingHash < Hash
  attr_accessor :duplicate_check_off
  def []=(key, value)
    if !duplicate_check_off && has_key?(key) then
      fail "Failed: Found duplicate key \"#{key}\" while parsing json! Please cleanup your JSON input!"
    end
    super
  end
end

json = '{"a": 1, "a": 2}'  # duplicate!
hash = JSON.parse(json, { object_class:DuplicateCheckingHash }) # will raise

json = '{"a": 1, "b": 2}'
hash = JSON.parse(json, { object_class:DuplicateCheckingHash })
hash.duplicate_check_off = true # make updateable again
hash["a"] = 42 # won't raise
Run Code Online (Sandbox Code Playgroud)