0ef772ff6e773b119f6f7af85a9674f0290cd6df
[p5sagit/Config-Any.git] / lib / Config / Any / JSON.pm
1 package Config::Any::JSON;
2
3 use strict;
4 use warnings;
5
6 use base 'Config::Any::Base';
7
8 =head1 NAME
9
10 Config::Any::JSON - Load JSON config files
11
12 =head1 DESCRIPTION
13
14 Loads 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
30 return an array of valid extensions (C<json>, C<jsn>).
31
32 =cut
33
34 sub extensions {
35     return qw( json jsn );
36 }
37
38 =head2 load( $file )
39
40 Attempts to load C<$file> as a JSON file.
41
42 =cut
43
44 sub 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
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
60     eval { require JSON::XS; };
61     unless( $@ ) {
62         my $decoder = JSON::XS->new->relaxed;
63         return $decoder->decode( $content );
64     }
65
66     eval { require JSON::Syck; };
67     unless( $@ ) {
68         return JSON::Syck::Load( $content );
69     }
70
71     require JSON;
72     eval { JSON->VERSION( 2 ); };
73     return $@ ? JSON::jsonToObj( $content ) : JSON::from_json( $content );
74 }
75
76 =head2 requires_any_of( )
77
78 Specifies that this modules requires one of,  L<JSON::DWIW>, L<JSON::XS>,
79 L<JSON::Syck> or L<JSON> in order to work.
80
81 =cut
82
83 sub requires_any_of { 'JSON::DWIW', 'JSON::XS', 'JSON::Syck', 'JSON' }
84
85 =head1 AUTHOR
86
87 Brian Cassidy E<lt>bricas@cpan.orgE<gt>
88
89 =head1 COPYRIGHT AND LICENSE
90
91 Copyright 2006-2010 by Brian Cassidy
92
93 This library is free software; you can redistribute it and/or modify
94 it under the same terms as Perl itself. 
95
96 =head1 SEE ALSO
97
98 =over 4 
99
100 =item * L<Catalyst>
101
102 =item * L<Config::Any>
103
104 =item * L<JSON::DWIW>
105
106 =item * L<JSON::XS>
107
108 =item * L<JSON::Syck>
109
110 =item * L<JSON>
111
112 =back
113
114 =cut
115
116 1;