Last active
August 29, 2015 14:05
-
-
Save stephanwehner/dc2ee28d08bddd5d3aa0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example run: