handle UTF-8 data in JSON correctly
[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
3a27e96d 48 open( my $fh, '<', $file ) or die $!;
49 binmode $fh;
f0e3c221 50 my $content = do { local $/; <$fh> };
51 close $fh;
52
4473d906 53 if ( eval { require JSON::DWIW } ) {
49ae6583 54 my $decoder = JSON::DWIW->new;
55 my ( $data, $error ) = $decoder->from_json( $content );
56 die $error if $error;
57 return $data;
58 }
4473d906 59 elsif ( eval { require JSON::XS } ) {
3a27e96d 60 my $decoder = JSON::XS->new->utf8->relaxed;
49ae6583 61 return $decoder->decode( $content );
f0e3c221 62 }
4473d906 63 elsif ( eval { require JSON::Syck } ) {
3a27e96d 64 require Encode;
65 return JSON::Syck::Load( Encode::decode('UTF-8', $content ) );
f0e3c221 66 }
4473d906 67 elsif ( eval { require JSON::PP; JSON::PP->VERSION( 2 ); } ) {
3a27e96d 68 my $decoder = JSON::PP->new->utf8->relaxed;
a8ffcd3b 69 return $decoder->decode( $content );
70 }
d49610ab 71 require JSON;
4473d906 72 if ( eval { JSON->VERSION( 2 ) } ) {
3a27e96d 73 return JSON::decode_json( $content );
4473d906 74 }
75 else {
76 return JSON::jsonToObj( $content );
77 }
f0e3c221 78}
79
dcfb1d1d 80=head2 requires_any_of( )
72628dc7 81
49ae6583 82Specifies that this modules requires one of, L<JSON::DWIW>, L<JSON::XS>,
83L<JSON::Syck> or L<JSON> in order to work.
72628dc7 84
85=cut
86
a8ffcd3b 87sub requires_any_of { 'JSON::DWIW', 'JSON::XS', 'JSON::Syck', 'JSON::PP', 'JSON' }
72628dc7 88
f0e3c221 89=head1 AUTHOR
90
a918b0b8 91Brian Cassidy E<lt>bricas@cpan.orgE<gt>
f0e3c221 92
93=head1 COPYRIGHT AND LICENSE
94
3d43e104 95Copyright 2006-2016 by Brian Cassidy
f0e3c221 96
97This library is free software; you can redistribute it and/or modify
98it under the same terms as Perl itself.
99
100=head1 SEE ALSO
101
102=over 4
103
104=item * L<Catalyst>
105
106=item * L<Config::Any>
107
49ae6583 108=item * L<JSON::DWIW>
109
110=item * L<JSON::XS>
f0e3c221 111
112=item * L<JSON::Syck>
113
49ae6583 114=item * L<JSON>
d49610ab 115
f0e3c221 116=back
117
118=cut
119
1201;