Skip to content

Instantly share code, notes, and snippets.

@stephanwehner
Last active August 29, 2015 14:05
Show Gist options
  • Save stephanwehner/dc2ee28d08bddd5d3aa0 to your computer and use it in GitHub Desktop.
Save stephanwehner/dc2ee28d08bddd5d3aa0 to your computer and use it in GitHub Desktop.
# JSON hashes of course allow multiple values for the same key.
# Only one is kept
# E.g.
# > h = JSON.parse '{"a":1, "a":2}'
# => {"a"=>2}
#
# If you don't like that, you can use this :
require 'json'
class DuplicateEntryCatchingHash < Hash
def []=(k,v)
@a ||= []
raise JSON::ParserError, "Duplicate Hash Entry #{k}" if @a.include?(k.to_s)
@a << k
super k,v
end
end
if __FILE__ == $0
def show_example(s)
puts "> JSON.parse '#{s}', :object_class => DuplicateEntryCatchingHash"
begin
h = JSON.parse s, :object_class => DuplicateEntryCatchingHash
puts "=> #{h.inspect}"
rescue JSON::ParserError => e
puts "=> JSON::ParserError #{e}"
end
puts
end
show_example '{"a": 1}'
show_example '{"a": 1, "a": 2}'
show_example '{"a": 1, "a": {"b": 2}}'
show_example '{"a": 1, "a": {"b": 2, "b": 3}}'
end
@stephanwehner
Copy link
Author

Example run:

$ ruby duplicate_entry_catching_hash.rb
> JSON.parse '{"a": 1}', :object_class => DuplicateEntryCatchingHash
=> {"a"=>1}

> JSON.parse '{"a": 1, "a": 2}', :object_class => DuplicateEntryCatchingHash
=> JSON::ParserError Duplicate Hash Entry a

> JSON.parse '{"a": 1, "a": {"b": 2}}', :object_class => DuplicateEntryCatchingHash
=> JSON::ParserError Duplicate Hash Entry a

> JSON.parse '{"a": 1, "a": {"b": 2, "b": 3}}', :object_class => DuplicateEntryCatchingHash
=> JSON::ParserError Duplicate Hash Entry b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment