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