do not clobber $@ (RT #103061)
[p5sagit/Config-Any.git] / lib / Config / Any / JSON.pm
CommitLineData
f0e3c221 1package Config::Any::JSON;
2
3use strict;
4use warnings;
5
dcfb1d1d 6use base 'Config::Any::Base';
7
f0e3c221 8=head1 NAME
9
10Config::Any::JSON - Load JSON config files
11
12=head1 DESCRIPTION
13
14Loads JSON files. Example:
15
16 {
17 "name": "TestApp",
18 "Controller::Foo": {
19 "foo": "bar"
20 },
21 "Model::Baz": {
22 "qux": "xyzzy"
23 }
24 }
25
26=head1 METHODS
27
28=head2 extensions( )
29
30return an array of valid extensions (C<json>, C<jsn>).
31
32=cut
33
34sub extensions {
35 return qw( json jsn );
36}
37
38=head2 load( $file )
39
40Attempts to load C<$file> as a JSON file.
41
42=cut
43
44sub load {
45 my $class = shift;
46 my $file = shift;
47
48 open( my $fh, $file ) or die $!;
49 my $content = do { local $/; <$fh> };
50 close $fh;
51
49ae6583 52 eval { require JSON::DWIW; };
53 unless( $@ ) {
54 my $decoder = JSON::DWIW->new;
55 my ( $data, $error ) = $decoder->from_json( $content );
56 die $error if $error;
57 return $data;
58 }
59
d49610ab 60 eval { require JSON::XS; };
61 unless( $@ ) {
49ae6583 62 my $decoder = JSON::XS->new->relaxed;
63 return $decoder->decode( $content );
f0e3c221 64 }
d49610ab 65
66 eval { require JSON::Syck; };
67 unless( $@ ) {
f0e3c221 68 return JSON::Syck::Load( $content );
69 }
d49610ab 70
a8ffcd3b 71 eval { require JSON::PP; JSON::PP->VERSION( 2 ); };
72 unless( $@ ) {
73 my $decoder = JSON::PP->new->relaxed;
74 return $decoder->decode( $content );
75 }
76
d49610ab 77 require JSON;
78 eval { JSON->VERSION( 2 ); };
79 return $@ ? JSON::jsonToObj( $content ) : JSON::from_json( $content );
f0e3c221 80}
81
dcfb1d1d 82=head2 requires_any_of( )
72628dc7 83
49ae6583 84Specifies that this modules requires one of, L<JSON::DWIW>, L<JSON::XS>,
85L<JSON::Syck> or L<JSON> in order to work.
72628dc7 86
87=cut
88
a8ffcd3b 89sub requires_any_of { 'JSON::DWIW', 'JSON::XS', 'JSON::Syck', 'JSON::PP', 'JSON' }
72628dc7 90
f0e3c221 91=head1 AUTHOR
92
a918b0b8 93Brian Cassidy E<lt>bricas@cpan.orgE<gt>
f0e3c221 94
95=head1 COPYRIGHT AND LICENSE
96
a8ffcd3b 97Copyright 2006-2013 by Brian Cassidy
f0e3c221 98
99This library is free software; you can redistribute it and/or modify
100it under the same terms as Perl itself.
101
102=head1 SEE ALSO
103
104=over 4
105
106=item * L<Catalyst>
107
108=item * L<Config::Any>
109
49ae6583 110=item * L<JSON::DWIW>
111
112=item * L<JSON::XS>
f0e3c221 113
114=item * L<JSON::Syck>
115
49ae6583 116=item * L<JSON>
d49610ab 117
f0e3c221 118=back
119
120=cut
121
1221;