in reply to make duplicate JSON keys an error
JSON::Tiny::Subclassable is my fork of davido's JSON::Tiny to make it more easy to subclass usefully. In fact, I wrote it to usefully handle duplicate keys. But if in fact you want to throw an error for duplicates, it's not much extra effort...
use strict; use warnings; # A tied hash that dies if you try to insert a key that already exists +. { package Tie::Hash::NoOverwrite; use Tie::Hash (); use Carp; use parent -norequire, qw(Tie::StdHash); sub STORE { my ($hash, $key, $value) = @_; # Ignore these packages for the purpose of reporting errors local our @CARP_NOT = qw( JSON::MultiValueDie JSON::Tiny::Subclassable ); croak "Duplicate key: $key" if exists $hash->{$key}; $hash->{$key} = $value; } } # A JSON decoder that ties all hashes with Tie::Hash::NoOverwrite. { package JSON::MultiValueDie; use parent qw(JSON::Tiny::Subclassable); sub _new_hash { tie my %h, 'Tie::Hash::NoOverwrite'; return \%h } } my $json = JSON::MultiValueDie->new; $json->decode(q/ { "a":1, "b":2 } /); print $json->error || 'ok', "\n"; $json->decode(q/ { "a":1, "a":2 } /); print $json->error || 'ok', "\n";
|
|---|