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