String/Json.pm

filter: Statementstmt 100% 9 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 100% 12 / 12 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« String/Javascript.pm ↑ Summary String/Parse.pm »
1 #
2 # $Id$
3 #
4 # string::json Brik
5 #
6 package Metabrik::String::Json;
7 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 1 ▶use base qw(Metabrik);
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 sub brik_properties {
13 return {
14 revision => '$Revision$',
15 tags => [ qw(unstable encode decode) ],
16 author => 'GomoR <GomoR[at]metabrik.org>',
17 license => 'http://opensource.org/licenses/BSD-3-Clause',
18 commands => {
19 encode => [ qw($data_list|$data_hash) ],
20 decode => [ qw($data) ],
21 is_valid => [ qw($data) ],
22 },
23 attributes => {
24 use_utf8 => [ qw(0|1) ],
25 },
26 attributes_default => {
27 use_utf8 => 1,
28 },
29 require_modules => {
30 'JSON::XS' => [ ],
31 },
32 };
33 }
34  
35 sub encode {
36 my $self = shift;
37 my ($data) = @_;
38  
39 $self->brik_help_run_undef_arg('encode', $data) or return;
40 $self->brik_help_run_invalid_arg('encode', $data, 'ARRAY', 'HASH')
41 or return;
42  
43 $self->log->debug("encode: data[$data]");
44  
45 my $encoded = '';
46 eval {
47 my $j = JSON::XS->new;
48 $j->relaxed(1);
49 $j->utf8($self->use_utf8);
50 $encoded = $j->encode($data);
51 };
52 if ($@) {
53 chomp($@);
54 return $self->log->error("encode: unable to encode JSON: $@");
55 }
56  
57 return $encoded;
58 }
59  
60 sub decode {
61 my $self = shift;
62 my ($data) = @_;
63  
64 $self->brik_help_run_undef_arg('decode', $data) or return;
65  
66 $self->log->debug("decode: data[$data]");
67  
68 my $decoded = '';
69 eval {
70 my $j = JSON::XS->new;
71 $j->relaxed(1);
72 $j->utf8($self->use_utf8);
73 $decoded = $j->decode($data);
74 };
75 if ($@) {
76 chomp($@);
77 return $self->log->error("decode: unable to decode JSON: $@, data[$data]");
78 }
79  
80 return $decoded;
81 }
82  
83 sub is_valid {
84 my $self = shift;
85 my ($data) = @_;
86  
87 $self->brik_help_run_undef_arg('is_valid', $data) or return;
88  
89 $self->log->debug("is_valid: data[$data]");
90  
91 eval {
92 $self->decode($data);
93 };
94 if ($@) {
95 return 0;
96 }
97  
98 return 1;
99 }
100  
101 1;
102  
103 __END__
« String/Javascript.pm ↑ Summary String/Parse.pm »