1 package OpenSRF::Utils::JSON;
4 my $parser = JSON::XS->new;
5 $parser->ascii(1); # output \u escaped strings for any char with a value over 127
6 $parser->allow_nonref(1); # allows non-reference values to equate to themselves (see perldoc)
9 my $JSON_CLASS_KEY = '__c';
10 my $JSON_PAYLOAD_KEY = '__p';
15 OpenSRF::Utils::JSON - Bucket-o-Routines for JSON
28 my( $class, $string ) = @_;
29 my $perl = $class->rawJSON2perl($string);
30 return $class->JSONObject2Perl($perl);
38 my( $class, $obj ) = @_;
39 my $json = $class->perl2JSONObject($obj);
40 return $class->rawPerl2JSON($json);
50 return undef unless defined $json and $json !~ /^\s*$/o;
51 return $parser->decode($json);
59 my ($class, $perl) = @_;
60 return $parser->encode($perl);
67 if( $ref eq 'HASH' ) {
68 if( defined($obj->{$JSON_CLASS_KEY})) {
69 my $cls = $obj->{$JSON_CLASS_KEY};
72 if( $obj = $class->JSONObject2Perl($obj->{$JSON_PAYLOAD_KEY}) ) {
73 $cls = $class->lookup_class($cls) || $cls;
74 return bless(\$obj, $cls) unless ref($obj);
75 return bless($obj, $cls);
79 for my $k (keys %$obj) {
80 $obj->{$k} = $class->JSONObject2Perl($obj->{$k})
81 unless ref($obj->{$k}) eq 'JSON::XS::Boolean';
83 } elsif( $ref eq 'ARRAY' ) {
84 for my $i (0..scalar(@$obj) - 1) {
85 $obj->[$i] = $class->JSONObject2Perl($obj->[$i])
86 unless ref($obj->[$i]) eq 'JSON::XS::Boolean';
97 return $obj unless $ref;
99 return $obj if $ref eq 'JSON::XS::Boolean';
102 if(UNIVERSAL::isa($obj, 'HASH')) {
104 $newobj->{$_} = $class->perl2JSONObject($obj->{$_}) for (keys %$obj);
105 } elsif(UNIVERSAL::isa($obj, 'ARRAY')) {
107 $newobj->[$_] = $class->perl2JSONObject($obj->[$_]) for(0..scalar(@$obj) - 1);
110 if($ref ne 'HASH' and $ref ne 'ARRAY') {
111 $ref = $class->lookup_hint($ref) || $ref;
112 $newobj = {$JSON_CLASS_KEY => $ref, $JSON_PAYLOAD_KEY => $newobj};
119 return $parser->true();
123 return $parser->false();
126 sub register_class_hint {
129 $_class_map{hints}{$args{hint}} = \%args;
130 $_class_map{classes}{$args{name}} = \%args;
136 return $_class_map{hints}{$hint}{name}
142 return $_class_map{classes}{$class}{hint}
145 sub _json_hint_to_class {
149 return $_class_map{hints}{$hint}{name} if (exists $_class_map{hints}{$hint});
151 $type = 'hash' if ($type eq '}');
152 $type = 'array' if ($type eq ']');
154 OpenSRF::Utils::JSON->register_class_hint(name => $hint, hint => $hint, type => $type);