]> git.evergreen-ils.org Git - Evergreen.git/blob - OpenSRF/src/perlmods/JSON.pm
a43f48fb02739a10de7e4633a86cf4aacb98a025
[Evergreen.git] / OpenSRF / src / perlmods / JSON.pm
1 package JSON::number;
2 sub new {
3         my $class = shift;
4         my $x = shift || $class;
5         return bless \$x => __PACKAGE__;
6 }
7
8 use overload ( '""' => \&toString );
9
10 sub toString { defined($_[1]) ? ${$_[1]} : ${$_[0]} }
11
12 package JSON::bool::true;
13 sub new { return bless {} => __PACKAGE__ }
14 use overload ( '""' => \&toString );
15 use overload ( 'bool' => sub { 1 } );
16 use overload ( '0+' => sub { 1 } );
17
18 sub toString { 'true' }
19
20 package JSON::bool::false;
21 sub new { return bless {} => __PACKAGE__ }
22 use overload ( '""' => \&toString );
23 use overload ( 'bool' => sub { 0 } );
24 use overload ( '0+' => sub { 0 } );
25
26 sub toString { 'false' }
27
28 package JSON;
29 use vars qw/%_class_map/;
30
31 sub register_class_hint {
32         my $class = shift;
33         my %args = @_;
34
35         $_class_map{hints}{$args{hint}} = \%args;
36         $_class_map{classes}{$args{name}} = \%args;
37 }
38
39 sub _JSON_regex {
40         my $string = shift;
41
42         $string =~ s/^\s* ( 
43                            {                            | # start object
44                            \[                           | # start array
45                            -?\d+\.?\d*                  | # number literal
46                            "(?:(?:\\[\"])|[^\"])*"      | # string literal
47                            (?:\/\*.+?\*\/)              | # C comment
48                            true                         | # bool true
49                            false                        | # bool false
50                            null                         | # undef()
51                            :                            | # object key-value sep
52                            ,                            | # list sep
53                            \]                           | # array end
54                            }                              # object end
55                         )
56                  \s*//sox;
57         return ($string,$1);
58 }
59
60 sub _json_hint_to_class {
61         my $type = shift;
62         my $hint = shift;
63
64         return $_class_map{hints}{$hint}{name} if (exists $_class_map{hints}{$hint});
65         
66         $type = 'hash' if ($type eq '}');
67         $type = 'array' if ($type eq ']');
68
69         JSON->register_class_hint(name => $hint, hint => $hint, type => $type);
70
71         return $hint;
72 }
73
74 sub JSON2perl {
75         my $class = shift;
76         local $_ = shift;
77
78         s/(?<!\\)\$/\\\$/gmo; # fixup $ for later
79         s/(?<!\\)\@/\\\@/gmo; # fixup @ for later
80         s/(?<!\\)\%/\\\%/gmo; # fixup % for later
81
82         # Convert JSON Unicode...
83         s/\\u(\d{4})/chr(hex($1))/esog;
84
85         # handle class blessings
86         s/\/\*--\s*S\w*?\s+\S+\s*--\*\// bless(/sog;
87         s/(\]|\}|")\s*\/\*--\s*E\w*?\s+(\S+)\s*--\*\//$1 => _json_hint_to_class("$1", "$2")) /sog;
88
89         my $re = qr/((?<!\\)"(?>(?<=\\)"|[^"])*(?<!\\)")/;
90         # Grab strings...
91         my @strings = /$re/sog;
92
93         # Replace with code...
94         #s/"(?:(?:\\[\"])|[^\"])*"/ do{ \$t = '"'.shift(\@strings).'"'; eval \$t;} /sog;
95         s/$re/ eval shift(\@strings) /sog;
96
97         # Perlify hash notation
98         s/:/ => /sog;
99
100         # Do numbers...
101 #       s/\b(-?\d+\.?\d*)\b/ JSON::number::new($1) /sog;
102
103         # Change javascript stuff to perl...
104         s/null/ undef /sog;
105         s/true/ bless( {}, "JSON::bool::true") /sog;
106         s/false/ bless( {}, "JSON::bool::false") /sog;
107
108         my $ret;
109         return eval '$ret = '.$_;
110 }
111
112 sub old_JSON2perl {
113         my ($class, $json) = @_;
114
115         if (!defined($json)) {
116                 return undef;
117         }
118
119         $json =~ s/(?<!\\)\$/\\\$/gmo; # fixup $ for later
120         $json =~ s/(?<!\\)\@/\\\@/gmo; # fixup @ for later
121         $json =~ s/(?<!\\)\%/\\\%/gmo; # fixup % for later
122
123         my @casts;
124         my $casting_depth = 0;
125         my $current_cast;
126         my $element;
127         my $output = '';
128         while (($json,$element) = _JSON_regex($json)) {
129
130                 last unless ($element);
131
132                 if ($element eq 'null') {
133                         $output .= ' undef() ';
134                         next;
135                 } elsif ($element =~ /^\/\*--\s*S\w*?\s+(\w+)\s*--\*\/$/) {
136                         my $hint = $1;
137                         if (exists $_class_map{hints}{$hint}) {
138                                 $casts[$casting_depth] = $hint;
139                                 $output .= ' bless(';
140                         }
141                         next;
142                 } elsif ($element =~ /^\/\*/) {
143                         next;
144                 } elsif ($element =~ /^\d/) {
145                         $output .= "do { JSON::number::new($element) }";
146                         next;
147                 } elsif ($element eq '{' or $element eq '[') {
148                         $casting_depth++;
149                 } elsif ($element eq '}' or $element eq ']') {
150                         $casting_depth--;
151                         my $hint = $casts[$casting_depth];
152                         $casts[$casting_depth] = undef;
153                         if (defined $hint and exists $_class_map{hints}{$hint}) {
154                                 $output .= $element . ',"'. $_class_map{hints}{$hint}{name} . '")';
155                                 next;
156                         }
157                 } elsif ($element eq ':') {
158                         $output .= ' => ';
159                         next;
160                 } elsif ($element eq 'true') {
161                         $output .= 'bless( {}, "JSON::bool::true")';
162                         next;
163                 } elsif ($element eq 'false') {
164                         $output .= 'bless( {}, "JSON::bool::false")';
165                         next;
166                 }
167                 
168                 $output .= $element;
169         }
170
171         return eval $output;
172 }
173
174 sub perl2JSON {
175         my ($class, $perl, $strict) = @_;
176
177         my $output = '';
178         if (!defined($perl)) {
179                 $output = '' if $strict;
180                 $output = 'null' unless $strict;
181         } elsif (ref($perl) and ref($perl) =~ /^JSON/) {
182                 $output .= $perl;
183         } elsif ( ref($perl) && exists($_class_map{classes}{ref($perl)}) ) {
184                 $output .= '/*--S '.$_class_map{classes}{ref($perl)}{hint}.'--*/';
185                 if (lc($_class_map{classes}{ref($perl)}{type}) eq 'hash') {
186                         my %hash =  %$perl;
187                         $output .= perl2JSON(undef,\%hash, $strict);
188                 } elsif (lc($_class_map{classes}{ref($perl)}{type}) eq 'array') {
189                         my @array =  @$perl;
190                         $output .= perl2JSON(undef,\@array, $strict);
191                 }
192                 $output .= '/*--E '.$_class_map{classes}{ref($perl)}{hint}.'--*/';
193         } elsif (ref($perl) and ref($perl) =~ /HASH/) {
194                 $output .= '{';
195                 my $c = 0;
196                 for my $key (sort keys %$perl) {
197                         $output .= ',' if ($c); 
198                         
199                         $output .= '"'.$key.'":'.perl2JSON(undef,$$perl{$key}, $strict);
200                         $c++;
201                 }
202                 $output .= '}';
203         } elsif (ref($perl) and ref($perl) =~ /ARRAY/) {
204                 $output .= '[';
205                 my $c = 0;
206                 for my $part (@$perl) {
207                         $output .= ',' if ($c); 
208                         
209                         $output .= perl2JSON(undef,$part, $strict);
210                         $c++;
211                 }
212                 $output .= ']';
213         } elsif (ref($perl) and ("$perl" =~ /^([^=]+)=(\w+)/o)) {
214                 my $type = $2;
215                 my $name = $1;
216                 JSON->register_class_hint(name => $name, hint => $name, type => lc($type));
217                 $output .= perl2JSON(undef,$perl, $strict);
218         } else {
219                 $perl =~ s{\\}{\\\\}sgo;
220                 $perl =~ s/"/\\"/sgo;
221                 $perl =~ s/\t/\\t/sgo;
222                 $perl =~ s/\f/\\f/sgo;
223                 $perl =~ s/\r/\\r/sgo;
224                 $perl =~ s/\n/\\n/sgo;
225                 $perl =~ s/(\pM)/sprintf('\u%0.4x',ord($1))/sgoe;
226                 if (length($perl) < 10 and $perl =~ /^(?:\+|-)?\d*\.?\d+$/o and $perl !~ /^(?:\+|-)?0\d+/o ) {
227                         $output = $perl;
228                 } else {
229                         $output = '"'.$perl.'"';
230                 }
231         }
232
233         return $output;
234 }
235
236 my $depth = 0;
237 sub perl2prettyJSON {
238         my ($class, $perl, $nospace) = @_;
239         $perl ||= $class;
240
241         my $output = '';
242         if (!defined($perl)) {
243                 $output = "   "x$depth unless($nospace);
244                 $output .= 'null';
245         } elsif (ref($perl) and ref($perl) =~ /^JSON/) {
246                 $output = "   "x$depth unless($nospace);
247                 $output .= $perl;
248         } elsif ( ref($perl) && exists($_class_map{classes}{ref($perl)}) ) {
249                 $depth++;
250                 $output .= "\n";
251                 $output .= "   "x$depth;
252                 $output .= '/*--S '.$_class_map{classes}{ref($perl)}{hint}."--*/ ";
253                 if (lc($_class_map{classes}{ref($perl)}{type}) eq 'hash') {
254                         my %hash =  %$perl;
255                         $output .= perl2prettyJSON(\%hash,undef,1);
256                 } elsif (lc($_class_map{classes}{ref($perl)}{type}) eq 'array') {
257                         my @array =  @$perl;
258                         $output .= perl2prettyJSON(\@array,undef,1);
259                 }
260                 $output .= ' /*--E '.$_class_map{classes}{ref($perl)}{hint}.'--*/';
261                 $depth--;
262         } elsif (ref($perl) and ref($perl) =~ /HASH/) {
263                 $output .= "   "x$depth unless ($nospace);
264                 $output .= "{\n";
265                 my $c = 0;
266                 $depth++;
267                 for my $key (sort keys %$perl) {
268                         $output .= ",\n" if ($c); 
269                         
270                         $output .= perl2prettyJSON($key)." : ".perl2prettyJSON($$perl{$key}, undef, 1);
271                         $c++;
272                 }
273                 $depth--;
274                 $output .= "\n";
275                 $output .= "   "x$depth;
276                 $output .= '}';
277         } elsif (ref($perl) and ref($perl) =~ /ARRAY/) {
278                 $output .= "   "x$depth unless ($nospace);
279                 $output .= "[\n";
280                 my $c = 0;
281                 $depth++;
282                 for my $part (@$perl) {
283                         $output .= ",\n" if ($c); 
284                         
285                         $output .= perl2prettyJSON($part);
286                         $c++;
287                 }
288                 $depth--;
289                 $output .= "\n";
290                 $output .= "   "x$depth;
291                 $output .= "]";
292         } elsif (ref($perl) and "$perl" =~ /^([^=]+)=(\w{4,5})\(0x/) {
293                 my $type = $2;
294                 my $name = $1;
295                 register_class_hint(undef, name => $name, hint => $name, type => lc($type));
296                 $output .= perl2prettyJSON(undef,$perl);
297         } else {
298                 $perl =~ s/\\/\\\\/sgo;
299                 $perl =~ s/"/\\"/sgo;
300                 $perl =~ s/\t/\\t/sgo;
301                 $perl =~ s/\f/\\f/sgo;
302                 $perl =~ s/\r/\\r/sgo;
303                 $perl =~ s/\n/\\n/sgo;
304                 $perl =~ s/(\pM)/sprintf('\u%0.4x',ord($1))/sgoe;
305                 $output .= "   "x$depth unless($nospace);
306                 if (length($perl) < 10 and $perl =~ /^(?:\+|-)?\d*\.?\d+$/o and $perl !~ /^(?:\+|-)?0\d+/o ) {
307                         $output = $perl;
308                 } else {
309                         $output = '"'.$perl.'"';
310                 }
311                 $output .= '"'.$perl.'"';
312         }
313
314         return $output;
315 }
316
317 1;