summaryrefslogtreecommitdiffstats
path: root/qooxdoo/source/perl/JSON.pm
blob: 59686e0a3932aad6487cc2ba55508ed7fccc22eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
package JSON;

use strict;
use base qw(Exporter);

@JSON::EXPORT = qw(objToJson jsonToObj);

use vars qw($AUTOCONVERT $VERSION $UnMapping $BareKey $QuotApos
            $ExecCoderef $SkipInvalid $Pretty $Indent $Delimiter
            $KeySort $ConvBlessed $SelfConvert $UTF8 $SingleQuote);

$VERSION = '1.14';

$AUTOCONVERT = 1;
$SkipInvalid = 0;
$ExecCoderef = 0;
$Pretty      = 0; # pretty-print mode switch
$Indent      = 2; # (for pretty-print)
$Delimiter   = 2; # (for pretty-print)  0 => ':', 1 => ': ', 2 => ' : '
$UnMapping   = 0; # 
$BareKey     = 0; # 
$QuotApos    = 0; # 
$KeySort     = undef; # Code-ref to provide sort ordering in converter
$UTF8        = 0;
$SingleQuote = 0;

my $USE_UTF8;

BEGIN {
    $USE_UTF8 = $] >= 5.008 ? 1 : 0;
    sub USE_UTF8 {  $USE_UTF8; }
}

use JSON::Parser;
use JSON::Converter;

my $parser; # JSON => Perl
my $conv;   # Perl => JSON


##############################################################################
# CONSTRCUTOR - JSON objects delegate all processes
#                   to JSON::Converter and JSON::Parser.
##############################################################################

sub new {
    my $class = shift;
    my %opt   = @_;
    bless {
        conv   => undef,  # JSON::Converter [perl => json]
        parser => undef,  # JSON::Parser    [json => perl]
        # below fields are for JSON::Converter
        autoconv    => $AUTOCONVERT,
        skipinvalid => $SkipInvalid,
        execcoderef => $ExecCoderef,
        pretty      => $Pretty     ,
        indent      => $Indent     ,
        delimiter   => $Delimiter  ,
        keysort     => $KeySort    ,
        convblessed => $ConvBlessed,
        selfconvert => $SelfConvert,
        singlequote => $SingleQuote,
        # below fields are for JSON::Parser
        unmapping   => $UnMapping,
        quotapos    => $QuotApos ,
        barekey     => $BareKey  ,
        # common options
        utf8        => $UTF8     ,
        # overwrite
        %opt,
    }, $class;
}


##############################################################################
# METHODS
##############################################################################

*parse_json = \&jsonToObj;

*to_json    = \&objToJson;

sub jsonToObj {
    my $self = shift;
    my $js   = shift;

    if(!ref($self)){ # class method
        my $opt = __PACKAGE__->_getParamsForParser($js);
        $js = $self;
        $parser ||= new JSON::Parser;
        $parser->jsonToObj($js, $opt);
    }
    else{ # instance method
        my $opt = $self->_getParamsForParser($_[0]);
        $self->{parser} ||= ($parser ||= JSON::Parser->new);
        $self->{parser}->jsonToObj($js, $opt);
    }
}


sub objToJson {
    my $self = shift || return;
    my $obj  = shift;

    if(ref($self) !~ /JSON/){ # class method
        my $opt = __PACKAGE__->_getParamsForConverter($obj);
        $obj  = $self;
        $conv ||= JSON::Converter->new();
        $conv->objToJson($obj, $opt);
    }
    else{ # instance method
        my $opt = $self->_getParamsForConverter($_[0]);
        $self->{conv}
         ||= JSON::Converter->new( %$opt );
        $self->{conv}->objToJson($obj, $opt);
    }
}


#######################


sub _getParamsForParser {
    my ($self, $opt) = @_;
    my $params;

    if(ref($self)){ # instance
        my @names = qw(unmapping quotapos barekey utf8);
        my ($unmapping, $quotapos, $barekey, $utf8) = @{$self}{ @names };
        $params = {
            unmapping => $unmapping, quotapos => $quotapos,
            barekey   => $barekey,   utf8     => $utf8,
        };
    }
    else{ # class
        $params = {
            unmapping => $UnMapping, barekey => $BareKey,
            quotapos  => $QuotApos,  utf8    => $UTF8,
        };
    }

    if($opt and ref($opt) eq 'HASH'){
        for my $key ( keys %$opt ){
            $params->{$key} = $opt->{$key};
        }
    }

    return $params;
}


sub _getParamsForConverter {
    my ($self, $opt) = @_;
    my $params;

    if(ref($self)){ # instance
        my @names
         = qw(pretty indent delimiter autoconv keysort convblessed selfconvert utf8 singlequote);
        my ($pretty, $indent, $delimiter, $autoconv,
                $keysort, $convblessed, $selfconvert, $utf8, $singlequote)
                                                           = @{$self}{ @names };
        $params = {
            pretty      => $pretty,       indent      => $indent,
            delimiter   => $delimiter,    autoconv    => $autoconv,
            keysort     => $keysort,      convblessed => $convblessed,
            selfconvert => $selfconvert,  utf8        => $utf8,
            singlequote => $singlequote,
        };
    }
    else{ # class
        $params = {
            pretty      => $Pretty,       indent      => $Indent,
            delimiter   => $Delimiter,    autoconv    => $AUTOCONVERT,
            keysort     => $KeySort,      convblessed => $ConvBlessed,
            selfconvert => $SelfConvert,  utf8        => $UTF8,
            singlequote => $SingleQuote, 
        };
    }

    if($opt and ref($opt) eq 'HASH'){
        for my $key ( keys %$opt ){
            $params->{$key} = $opt->{$key};
        }
    }

    return $params;
}

##############################################################################
# ACCESSOR
##############################################################################
BEGIN{
    for my $name (qw/autoconv pretty indent delimiter 
                  unmapping keysort convblessed selfconvert singlequote/)
    {
        eval qq{
            sub $name { \$_[0]->{$name} = \$_[1] if(defined \$_[1]); \$_[0]->{$name} }
        };
    }
}

##############################################################################
# NON STRING DATA
##############################################################################

# See JSON::Parser for JSON::NotString.

sub Number {
    my $num = shift;

    return undef if(!defined $num);

    if(    $num =~ /^-?(?:\d+)(?:\.\d*)?(?:[eE][-+]?\d+)?$/
        or $num =~ /^0[xX](?:[0-9a-zA-Z])+$/                 )
    {
        return bless {value => $num}, 'JSON::NotString';
    }
    else{
        return undef;
    }
}

sub True {
    bless {value => 'true'}, 'JSON::NotString';
}

sub False {
    bless {value => 'false'}, 'JSON::NotString';
}

sub Null {
    bless {value => undef}, 'JSON::NotString';
}

##############################################################################
1;
__END__

=pod

=head1 NAME

JSON - parse and convert to JSON (JavaScript Object Notation).

=head1 SYNOPSIS

 use JSON;
 
 $obj = {
    id   => ["foo", "bar", { aa => 'bb'}],
    hoge => 'boge'
 };
 
 $js  = objToJson($obj);
 # this is {"id":["foo","bar",{"aa":"bb"}],"hoge":"boge"}.
 $obj = jsonToObj($js);
 # the data structure was restored.
 
 # OOP
 
 my $json = new JSON;
 
 $obj = {id => 'foo', method => 'echo', params => ['a','b']};
 $js  = $json->objToJson($obj);
 $obj = $json->jsonToObj($js);
 
 # pretty-printing
 $js = $json->objToJson($obj, {pretty => 1, indent => 2});

 $json = JSON->new(pretty => 1, delimiter => 0);
 $json->objToJson($obj);


=head1 TRANSITION PLAN

In the next large update version, JSON and JSONRPC modules are split.

  JSON::Parser and JSON::Converter are deleted from JSON dist.
  JSON and JSON::PP in JSON dist.

  JSON becomes wrapper to JSON::XS and/or JSON::PP.

  JSONRPC* and Apache::JSONRPC are deleted from JSON dist.
  JSONRPC::Client, JSONRPC::Server and JSONRPC::Procedure in JSON::RPC dist.

  Modules in JSON::RPC dist supports JSONRPC protocol v1.1 and 1.0.


=head1 DESCRIPTION

This module converts between JSON (JavaScript Object Notation) and Perl
data structure into each other.
For JSON, See to http://www.crockford.com/JSON/.


=head1 METHODS

=over 4

=item new()

=item new( %options )

returns a JSON object. The object delegates the converting and parsing process
to L<JSON::Converter> and L<JSON::Parser>.

 my $json = new JSON;

C<new> can take some options.

 my $json = new JSON (autoconv => 0, pretty => 1);

Following options are supported:

=over 4

=item autoconv

See L</AUTOCONVERT> for more info.

=item skipinvalid

C<objToJson()> does C<die()> when it encounters any invalid data
(for instance, coderefs). If C<skipinvalid> is set with true,
the function convets these invalid data into JSON format's C<null>.

=item execcoderef

C<objToJson()> does C<die()> when it encounters any code reference.
However, if C<execcoderef> is set with true, executes the coderef
and uses returned value.

=item pretty

See L</PRETTY PRINTING> for more info.

=item indent

See L</PRETTY PRINTING> for more info.

=item delimiter

See L</PRETTY PRINTING> for more info.

=item keysort

See L</HASH KEY SORT ORDER> for more info.

=item convblessed

See L</BLESSED OBJECT> for more info.

=item selfconvert

See L</BLESSED OBJECT> for more info.

=item singlequote

See L</CONVERT WITH SINGLE QUOTES> for more info.

=back 


=item objToJson( $object )

=item objToJson( $object, $hashref )

takes perl data structure (basically, they are scalars, arrayrefs and hashrefs)
and returns JSON formated string.

 my $obj = [1, 2, {foo => bar}];
 my $js  = $json->objToJson($obj);
 # [1,2,{"foo":"bar"}]

By default, returned string is one-line. However, you can get pretty-printed
data with C<pretty> option. Please see below L</PRETTY PRINTING>.

 my $js  = $json->objToJson($obj, {pretty => 1, indent => 2});
 # [
 #   1,
 #   2,
 #   {
 #     "foo" : "bar"
 #   }
 # ]

=item jsonToObj( $js )

takes a JSON formated data and returns a perl data structure.


=item autoconv()

=item autoconv($bool)

This is an accessor to C<autoconv>. See L</AUTOCONVERT> for more info.

=item pretty()

=item pretty($bool)

This is an accessor to C<pretty>. It takes true or false.
When prrety is true, C<objToJson()> returns prrety-printed string.
See L</PRETTY PRINTING> for more info.

=item indent()

=item indent($integer)

This is an accessor to C<indent>.
See L</PRETTY PRINTING> for more info.

=item delimiter()

This is an accessor to C<delimiter>.
See L</PRETTY PRINTING> for more info.

=item unmapping()

=item unmapping($bool)

This is an accessor to C<unmapping>.
See L</UNMAPPING OPTION> for more info.

=item keysort()

=item keysort($coderef)

This is an accessor to C<keysort>.
See L</HASH KEY SORT ORDER> for more info.

=item convblessed()

=item convblessed($bool)

This is an accessor to C<convblessed>.
See L</BLESSED OBJECT> for more info.

=item selfconvert()

=item selfconvert($bool)

This is an accessor to C<selfconvert>.
See L</BLESSED OBJECT> for more info.

=item singlequote()

=item singlequote($bool)

This is an accessor to C<singlequote>.
See L</CONVERT WITH SINGLE QUOTES> for more info.


=back

=head1 MAPPING

 (JSON) {"param" : []}
 ( => Perl) {'param' => []};
 
 (JSON) {"param" : {}}
 ( => Perl) {'param' => {}};
 
 (JSON) {"param" : "string"}
 ( => Perl) {'param' => 'string'};
 
 JSON {"param" : null}
  => Perl {'param' => bless( {'value' => undef}, 'JSON::NotString' )};
  or {'param' => undef}
 
 (JSON) {"param" : true}
 ( => Perl) {'param' => bless( {'value' => 'true'}, 'JSON::NotString' )};
  or {'param' => 1}
 
 (JSON) {"param" : false}
 ( => Perl) {'param' => bless( {'value' => 'false'}, 'JSON::NotString' )};
  or {'param' => 2}
 
 (JSON) {"param" : 0xff}
 ( => Perl) {'param' => 255};

 (JSON) {"param" : 010}
 ( => Perl) {'param' => 8};

These JSON::NotString objects are overloaded so you don't care about.
Since 1.00, L</UnMapping option> is added. When that option is set,
{"param" : null} will be converted into {'param' => undef}, insted of 
{'param' => bless( {'value' => undef}, 'JSON::NotString' )}.


Perl's C<undef> is converted to 'null'.


=head1 PRETTY PRINTING

If you'd like your JSON output to be pretty-printed, pass the C<pretty>
parameter to objToJson(). You can affect the indentation (which defaults to 2)
by passing the C<indent> parameter to objToJson().

  my $str = $json->objToJson($obj, {pretty => 1, indent => 4});

In addition, you can set some number to C<delimiter> option.
The available numbers are only 0, 1 and 2.
In pretty-printing mode, when C<delimiter> is 1, one space is added
after ':' in object keys. If C<delimiter> is 2, it is ' : ' and
0 is ':' (default is 2). If you give 3 or more to it, the value
is taken as 2.


=head1 AUTOCONVERT

By default, $JSON::AUTOCONVERT is true.

 (Perl) {num => 10.02}
 ( => JSON) {"num" : 10.02}

it is not C<{"num" : "10.02"}>.

But set false value with $JSON::AUTOCONVERT:

 (Perl) {num => 10.02}
 ( => JSON) {"num" : "10.02"}

it is not C<{"num" : 10.02}>.

You can explicitly sepcify:

 $obj = {
    id     => JSON::Number(10.02),
    bool1  => JSON::True,
    bool2  => JSON::False,
    noval  => JSON::Null,
 };

 $json->objToJson($obj);
 # {"noval" : null, "bool2" : false, "bool1" : true, "id" : 10.02}

C<JSON::Number()> returns C<undef> when an argument invalid format.

=head1 UNMAPPING OPTION

By default, $JSON::UnMapping is false and JSON::Parser converts
C<null>, C<true>, C<false> into C<JSON::NotString> objects.
You can set true into $JSON::UnMapping to stop the mapping function.
In that case, JSON::Parser will convert C<null>, C<true>, C<false>
into C<undef>, 1, 0.

=head1 BARE KEY OPTION

You can set a true value into $JSON::BareKey for JSON::Parser to parse
bare keys of objects.

 local $JSON::BareKey = 1;
 $obj = jsonToObj('{foo:"bar"}');

=head1 SINGLE QUOTATION OPTION

You can set a true value into $JSON::QuotApos for JSON::Parser to parse
any keys and values quoted by single quotations.

 local $JSON::QuotApos = 1;
 $obj = jsonToObj(q|{"foo":'bar'}|);
 $obj = jsonToObj(q|{'foo':'bar'}|);

With $JSON::BareKey:

 local $JSON::BareKey  = 1;
 local $JSON::QuotApos = 1;
 $obj = jsonToObj(q|{foo:'bar'}|);

=head1 HASH KEY SORT ORDER

By default objToJSON will serialize hashes with their keys in random
order.  To control the ordering of hash keys, you can provide a standard
'sort' function that will be used to control how hashes are converted.

You can provide either a fully qualified function name or a CODEREF to
$JSON::KeySort or $obj->keysort.

If you give any integers (excluded 0), the sort function will work as:

 sub { $a cmp $b }

Note that since the sort function is external to the JSON module the
magical $a and $b arguments will not be in the same package.  In order
to gain access to the sorting arguments, you must either:

  o use the ($$) prototype (slow)
  o Fully qualify $a and $b from the JSON::Converter namespace

See the documentation on sort for more information.

 local $JSON::KeySort = 'My::Package::sort_function';

 or

 local $JSON::KeySort = \&_some_function;

 sub sort_function {
    $JSON::Converter::a cmp $JSON::Converter::b;
 }

 or

 sub sort_function ($$) {
    my ($a, $b) = @_;

    $a cmp $b
 }

=head1 BLESSED OBJECT

By default, JSON::Converter doesn't deal with any blessed object
(returns C<undef> or C<null> in the JSON format).
If you use $JSON::ConvBlessed or C<convblessed> option,
the module can convert most blessed object (hashref or arrayref).

  local $JSON::ConvBlessed = 1;
  print objToJson($blessed);

This option slows down the converting speed.

If you use $JSON::SelfConvert or C<selfconvert> option,
the module will test for a C<toJson()> method on the object,
and will rely on this method to obtain the converted value of
the object.

=head1 UTF8

You can set a true value into $JSON::UTF8 for JSON::Parser
and JSON::Converter to set UTF8 flag into strings contain utf8.


=head1 CONVERT WITH SINGLE QUOTES

You can set a true value into $JSON::SingleQuote for JSON::Converter
to quote any keys and values with single quotations.

You want to parse single quoted JSON data, See L</SINGLE QUOTATION OPTION>.


=head1 EXPORT

C<objToJson>, C<jsonToObj>.

=head1 TODO

Which name is more desirable? JSONRPC or JSON::RPC.

SingleQuote and QuotApos...


=head1 SEE ALSO

L<http://www.crockford.com/JSON/>, L<JSON::Parser>, L<JSON::Converter>

If you want the speed and the saving of memory usage,
check L<JSON::Syck>.

=head1 ACKNOWLEDGEMENTS

I owe most JSONRPC idea to L<XMLRPC::Lite> and L<SOAP::Lite>.

SHIMADA pointed out many problems to me.

Mike Castle E<lt>dalgoda[at]ix.netcom.comE<gt> suggested
better packaging way.

Jeremy Muhlich E<lt>jmuhlich[at]bitflood.orgE<gt> help me
escaped character handling in JSON::Parser.

Adam Sussman E<lt>adam.sussman[at]ticketmaster.comE<gt>
suggested the octal and hexadecimal formats as number.
Sussman also sent the 'key sort' and 'hex number autoconv' patch
and 'HASH KEY SORT ORDER' section.

Tatsuhiko Miyagawa E<lt>miyagawa[at]bulknews.netE<gt>
taught a terrible typo and gave some suggestions.

David Wheeler E<lt>david[at]kineticode.comE<gt>
suggested me supporting pretty-printing and
gave a part of L<PRETTY PRINTING>.

Rusty Phillips E<lt>rphillips[at]edats.comE<gt>
suggested me supporting the query object other than CGI.pm
for JSONRPC::Transport::HTTP::CGI.

Felipe Gasper E<lt>gasperfm[at]uc.eduE<gt>
pointed to a problem of JSON::NotString with undef.
And show me patches for 'bare key option' & 'single quotation option'.

Yaman Saqqa E<lt>abulyomon[at]gmail.comE<gt>
helped my decision to support the bare key option.

Alden DoRosario E<lt>adorosario[at]chitika.comE<gt>
tought JSON::Conveter::_stringfy (<= 0.992) is very slow.

Brad Baxter sent to 'key sort' patch and thought a bug in JSON.

Jacob and Jay Buffington sent 'blessed object conversion' patch.

Thanks to Peter Edwards, IVAN, and all testers for bug reports.

Yann Kerherve sent 'selfconverter' patch(code, document and test).

Annocpan users comment on JSON pod. See http://annocpan.org/pod/JSON

And Thanks very much to JSON by JSON.org (Douglas Crockford) and
JSON-RPC by http://json-rpc.org/


=head1 AUTHOR

Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright 2005-2007 by Makamaka Hannyaharamitu

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself. 

=cut