1

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

{"a":{
"stateId":"b",
"countyId":["c"]
},"a":{
"stateId":"d",
"countyId":["e"]
}}

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

4

2 回答 2

5

有一种方法。不要使用通常的 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
于 2018-11-14T09:07:30.083 回答
0

这完全取决于字符串的格式。如果它像您发布的那样简单:

require 'json'

my_json =<<END_OF_JSON
{"a":{
"stateId":"b",
"countyId":["c"]
},"a":{
"stateId":"d",
"countyId":["e"]
},"b":{
"stateId":"x",
"countyId":["y"]
},"b":{
"stateId":"no",
"countyId":["no"]
}}
END_OF_JSON


results = {}

hash_strings = my_json.split("},")

hash_strings.each do |hash_str|
  hash_str.strip!

  hash_str = "{" + hash_str if not hash_str.start_with? "{"
  hash_str += "}}" if not hash_str.end_with? "}}"

  hash = JSON.parse(hash_str)

  hash.each do |key, val|
    results[key] = val if not results.keys.include? key
  end

end

p results

--output:--
{"a"=>{"stateId"=>"b", "countyId"=>["c"]}, "b"=>{"stateId"=>"x", "countyId"=>["y"]}}
于 2013-09-15T07:23:23.650 回答