1 package OpenSRF::Utils::JSON;
3 use vars qw/%_class_map/;
5 my $parser = JSON::XS->new;
6 $parser->ascii(1); # output \u escaped strings
7 $parser->allow_nonref(1);
10 return $parser->true();
14 return $parser->false();
17 sub register_class_hint {
20 $_class_map{hints}{$args{hint}} = \%args;
21 $_class_map{classes}{$args{name}} = \%args;
27 return $_class_map{hints}{$hint}{name}
33 return $_class_map{classes}{$class}{hint}
36 sub _json_hint_to_class {
40 return $_class_map{hints}{$hint}{name} if (exists $_class_map{hints}{$hint});
42 $type = 'hash' if ($type eq '}');
43 $type = 'array' if ($type eq ']');
45 OpenSRF::Utils::JSON->register_class_hint(name => $hint, hint => $hint, type => $type);
51 my $JSON_CLASS_KEY = '__c';
52 my $JSON_PAYLOAD_KEY = '__p';
55 my( $class, $string ) = @_;
56 my $perl = $class->rawJSON2perl($string);
57 return $class->JSONObject2Perl($perl);
61 my( $class, $obj ) = @_;
62 my $json = $class->perl2JSONObject($obj);
63 return $class->rawPerl2JSON($json);
70 if( $ref eq 'HASH' ) {
71 if( defined($obj->{$JSON_CLASS_KEY})) {
72 my $cls = $obj->{$JSON_CLASS_KEY};
75 if( $obj = $class->JSONObject2Perl($obj->{$JSON_PAYLOAD_KEY}) ) {
76 $cls = $class->lookup_class($cls) || $cls;
77 return bless(\$obj, $cls) unless ref($obj);
78 return bless($obj, $cls);
82 for my $k (keys %$obj) {
83 $obj->{$k} = $class->JSONObject2Perl($obj->{$k})
84 unless ref($obj->{$k}) eq 'JSON::XS::Boolean';
86 } elsif( $ref eq 'ARRAY' ) {
87 for my $i (0..scalar(@$obj) - 1) {
88 $obj->[$i] = $class->JSONObject2Perl($obj->[$i])
89 unless ref($obj->[$i]) eq 'JSON::XS::Boolean';
100 return $obj unless $ref;
102 return $obj if $ref eq 'JSON::XS::Boolean';
105 if(UNIVERSAL::isa($obj, 'HASH')) {
107 $newobj->{$_} = $class->perl2JSONObject($obj->{$_}) for (keys %$obj);
108 } elsif(UNIVERSAL::isa($obj, 'ARRAY')) {
110 $newobj->[$_] = $class->perl2JSONObject($obj->[$_]) for(0..scalar(@$obj) - 1);
113 if($ref ne 'HASH' and $ref ne 'ARRAY') {
114 $ref = $class->lookup_hint($ref) || $ref;
115 $newobj = {$JSON_CLASS_KEY => $ref, $JSON_PAYLOAD_KEY => $newobj};
125 return undef unless defined $json and $json !~ /^\s*$/o;
126 return $parser->decode($json);
130 my ($class, $perl) = @_;
131 return $parser->encode($perl);