Quiq/Json/Code.pm

filter: Statementstmt 95.7% 91 / 95 Branchbran 87.5% 42 / 48 Conditioncond 83.3% 5 / 6 MC/DCmcdc 66.6% 2 / 3 Subroutinesub 100% 13 / 13 Podpod 100% 5 / 5 totaltotal 92.9% 158 / 170 CC 29 SCAR 23.2
CC
29
Cov
93%
object
14.5
encode
14.0
code
2.0
CRAP 10.2
« Quiq/Formatter.pm ↑ Summary Quiq/Html/Widget/CheckBoxBar.pm »
1 # -----------------------------------------------------------------------------
2  
3 =encoding utf8
4  
5 =head1 NAME
6  
7 Quiq::Json::Code - Erzeuge JSON-Code in Perl
8  
9 =head1 BASE CLASS
10  
11 L<Quiq::Hash>
12  
13 =head1 SYNOPSIS
14  
15 =head2 Klasse laden und Objekt instantiieren
16  
17 use Quiq::Json::Code;
18
19 my $j = Quiq::Json::Code->new;
20  
21 =head2 JSON-Objekt via object()
22  
23 $json = $j->object(
24 pi => 3.14159,
25 str => 'Hello world!',
26 bool => \'true',
27 obj => $j->object(
28 id => 4711,
29 name => 'Wall',
30 numbers => [1..5],
31 ),
32 min => undef,
33 );
34  
35 erzeugt
36  
37 {
38 pi: 3.14159,
39 str: 'Hello world!',
40 bool: true,
41 obj: {
42 id: 4711,
43 name: 'Wall',
44 numbers: [1,2,3,4,5],
45 },
46 min: undefined,
47 }
48  
49 Bei der Methode $j->L<object|"object() - Erzeuge Code für JSON-Objekt">()
50  
51 =over 2
52  
53 =item *
54  
55 bleibt die Reihenfolge der Schlüssel/Wert-Paare erhalten
56  
57 =item *
58  
59 jedes Schlüssel/Wert-Paar beginnt auf einer eigenen Zeile und
60 wird eingerückt
61  
62 =back
63  
64 =head2 JSON-Datenstruktur via encode()
65  
66 $json = $j->encode({
67 pi => 3.14159,
68 str => 'Hello world!',
69 bool => \'true',
70 obj => {
71 id => 4711,
72 name => 'Wall',
73 numbers => [1..5],
74 },
75 min => undef,
76 });
77  
78 erzeugt
79  
80 {bool:true,min:undefined,obj:{id:4711,name:'Wall',numbers:[1,2,3,4,5]},pi:3.14159,str:'Hello world!'}
81  
82 Bei der Methode $j->L<encode|"encode() - Wandele Perl- in JavaScript-Datenstruktur">()
83  
84 =over 2
85  
86 =item *
87  
88 werden die Schlüssel/Wert-Paare von JSON-Objekten
89 alphanumerisch sortiert (bei {...} ist die Reihenfolge sonst
90 undefiniert)
91  
92 =item *
93  
94 gibt es keine Einrückung oder Leerraum nach dem :
95  
96 =back
97  
98 =head1 DESCRIPTION
99  
100 Die Klasse ermöglicht die präzise Erzeugung von JavaScript-Datenstrukturen
101 aus Perl heraus. Der Fokus liegt nicht auf der Übermittlung von Daten,
102 sondern auf der Einsetzung der Strukturen in JavaScript-Quelltexte.
103 Insofern gehen die Möglichketen der Klasse über JSON hinaus.
104 Die JavaScript-Klasse Chart.js arbeitet z.B. mit einer komplexen
105 Datenstruktur. Diese Struktur aus Perl heraus dynamisch erzeugen zu
106 können, war der Anlass für die Entwicklung dieser Klasse.
107 Das Perl-Modul JSON ist für diese Zwecke nicht geeignet, denn z.B.
108 kann eine JavaScript-Datenstruktur Referenzen auf (inline definierte)
109 JavaScript-Funktionen enthalten. Dies ist mit dieser Klasse möglich.
110 Weitere Vorteile dieser Klasse:
111  
112 =over 2
113  
114 =item *
115  
116 die Reihenfolge von Objektattributen bleibt erhalten
117  
118 =item *
119  
120 Werte können literal eingesetzt werden (z.B. Funktionsdefinionen,
121 spezielle Werte wie C<true>, C<false>, C<null> usw.)
122  
123 =item *
124  
125 lesbarerer Code
126  
127 =back
128  
129 =head1 EXAMPLE
130  
131 Ein realer Fall. Die Erzeugung einer Konfiguration für Chart.js. Wir
132 nutzen hier die Aliase o() und c() für die Methoden object() und code().
133  
134 my @dataSets;
135 my $title = 'Windspeed';
136 my $unit = 'm/s';
137 my $tMin = undef;
138 my $tMax = undef;
139 my $yMin = 0;
140 my $yMax = undef;
141
142 $json = $j->o(
143 type => 'line',
144 data => $j->o(
145 datasets => \@dataSets,
146 ),
147 options => $j->o(
148 maintainAspectRatio => \'false',
149 title => $j->o(
150 display => \'true',
151 text => $title,
152 fontSize => 16,
153 fontStyle => 'normal',
154 ),
155 tooltips => $j->o(
156 intersect => \'false',
157 displayColors => \'false',
158 backgroundColor => 'rgb(0,0,0,0.6)',
159 titleMarginBottom => 2,
160 callbacks => $j->o(
161 label => $j->c(qq~
162 function(tooltipItem,data) {
163 var i = tooltipItem.datasetIndex;
164 var label = data.datasets[i].label || '';
165 if (label)
166 label += ': ';
167 label += tooltipItem.value + ' $unit';
168 return label;
169 }
170 ~),
171 ),
172 ),
173 legend => $j->o(
174 display => \'false',
175 ),
176 scales => $j->o(
177 xAxes => [$j->o(
178 type => 'time',
179 ticks => $j->o(
180 minRotation => 30,
181 maxRotation => 60,
182 ),
183 time => $j->o(
184 min => $tMin,
185 max => $tMax,
186 minUnit => 'second',
187 displayFormats => $j->o(
188 second => 'YYYY-MM-DD HH:mm:ss',
189 minute => 'YYYY-MM-DD HH:mm',
190 hour => 'YYYY-MM-DD HH',
191 day => 'YYYY-MM-DD',
192 week => 'YYYY-MM-DD',
193 month => 'YYYY-MM',
194 quarter => 'YYYY [Q]Q',
195 year => 'YYYY',
196 ),
197 tooltipFormat => 'YYYY-MM-DD HH:mm:ss',
198 ),
199 )],
200 yAxes => [$j->o(
201 ticks => $j->o(
202 min => $yMin,
203 max => $yMax,
204 ),
205 scaleLabel => $j->o(
206 display => \'true',
207 labelString => $unit,
208 ),
209 )],
210 ),
211 ),
212 );
213  
214 erzeugt
215  
216 {
217 type: 'line',
218 data: {
219 datasets: [],
220 },
221 options: {
222 maintainAspectRatio: false,
223 title: {
224 display: true,
225 text: 'Windspeed',
226 fontSize: 16,
227 fontStyle: 'normal',
228 },
229 tooltips: {
230 intersect: false,
231 displayColors: false,
232 backgroundColor: 'rgb(0,0,0,0.6)',
233 titleMarginBottom: 2,
234 callbacks: {
235 label: function(tooltipItem,data) {
236 var i = tooltipItem.datasetIndex;
237 var label = data.datasets[i].label || '';
238 if (label)
239 label += ': ';
240 label += tooltipItem.value + ' m/s';
241 return label;
242 },
243 },
244 },
245 legend: {
246 display: false,
247 },
248 scales: {
249 xAxes: [{
250 type: 'time',
251 ticks: {
252 minRotation: 30,
253 maxRotation: 60,
254 },
255 time: {
256 min: undefined,
257 max: undefined,
258 minUnit: 'second',
259 displayFormats: {
260 second: 'YYYY-MM-DD HH:mm:ss',
261 minute: 'YYYY-MM-DD HH:mm',
262 hour: 'YYYY-MM-DD HH',
263 day: 'YYYY-MM-DD',
264 week: 'YYYY-MM-DD',
265 month: 'YYYY-MM',
266 quarter: 'YYYY [Q]Q',
267 year: 'YYYY',
268 },
269 tooltipFormat: 'YYYY-MM-DD HH:mm:ss',
270 },
271 }],
272 yAxes: [{
273 ticks: {
274 min: 0,
275 max: undefined,
276 },
277 scaleLabel: {
278 display: true,
279 labelString: 'm/s',
280 },
281 }],
282 },
283 },
284 }
285  
286 =cut
287  
288 # -----------------------------------------------------------------------------
289  
290 package Quiq::Json::Code;
291 7 ▶use base qw/Quiq::Hash/;
Subroutine BEGIN: called CC=1 SCAR=0.0
292  
293 7 ▶use v5.10;
Subroutine BEGIN: called CC=1 SCAR=0.0
294 7 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
295 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
296  
297 7 our $VERSION = '1.240';
298  
299 7 ▶use Quiq::Unindent;
Subroutine BEGIN: called CC=1 SCAR=0.0
300 7 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
301  
302 # -----------------------------------------------------------------------------
303  
304 =head1 METHODS
305  
306 =head2 Instantiierung
307  
308 =head3 new() - Konstruktor
309  
310 =head4 Synopsis
311  
312 $j = $class->new(@keyVal);
313  
314 =head4 Attributes
315  
316 =over 4
317  
318 =item indent => $n (Default: 4)
319  
320 Tiefe der Einrückung.
321  
322 =back
323  
324 =head4 Returns
325  
326 Objekt
327  
328 =head4 Description
329  
330 Instantiiere ein Objekt der Klasse und liefere eine Referenz
331 auf dieses Objekt zurück.
332  
333 =cut
334  
335 # -----------------------------------------------------------------------------
336  
337 8 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
338 8 my $class = shift;
339 # @_: @keyVal
340  
341 8 my $self = $class->SUPER::new(
342 indent => 4,
343 );
344 8 $self->set(@_);
345  
346 8 return $self;
347 }
348  
349 # -----------------------------------------------------------------------------
350  
351 =head2 Objektmethoden
352  
353 =head3 code() - Erzeuge Sourcecode für JSON-Datenstruktur
354  
355 =head4 Synopsis
356  
357 $code = $j->code($text); # Scalar-Kontext
358 ($codeS) = $j->code($text); # List-Kontext
359  
360 =head4 Alias
361  
362 c()
363  
364 =head4 Arguments
365  
366 =over 4
367  
368 =item $text
369  
370 Sourcecode, typischerweise mehrzeiliger JavaScript-Code.
371  
372 =back
373  
374 =head4 Returns
375  
376 Sourecode (String). Im List-Kontext eine Referenz auf den Code.
377  
378 =head4 Description
379  
380 Erzeuge Sourcecode, der in eine JSON-Datenstruktur eingebettet
381 werden kann, und liefere diesen zurück. Der Code
382  
383 =over 2
384  
385 =item *
386  
387 erhält die richtige Einrückung
388  
389 =item *
390  
391 wird "as is" eingebettet, also nicht gequotet
392  
393 =back
394  
395 =head4 Example
396  
397 Weise Funktionsreferenz an Objekt-Attribut zu
398  
399 $unit = 'm/s';
400 $json = $j->object(
401 label => $j->code(qq~
402 function(tooltipItem,data) {
403 var i = tooltipItem.datasetIndex;
404 var label = data.datasets[i].label || '';
405 if (label)
406 label += ': ';
407 label += tooltipItem.value + ' $unit';
408 return label;
409 }
410 ~),
411 ),
412  
413 liefert
414  
415 {
416 label: function(tooltipItem,data) {
417 var i = tooltipItem.datasetIndex;
418 var label = data.datasets[i].label || '';
419 if (label)
420 label += ': ';
421 label += tooltipItem.value + ' m/s';
422 return label;
423 },
424 }
425  
426 =cut
427  
428 # -----------------------------------------------------------------------------
429  
430 4 ▶sub code {
Subroutine code: called CC=2 SCAR=7.1
Pod documented
431 4 my ($self,$text) = @_;
432 4 my $code = Quiq::Unindent->trim($text);
433 4 ▶ return wantarray? \$code: $code;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 4 0 4
434 }
435  
436 {
437 7 ▶ no warnings 'once';
Subroutine BEGIN: called CC=1 SCAR=0.0
438 7 *c = \&code;
439 }
440  
441 # -----------------------------------------------------------------------------
442  
443 =head3 encode() - Wandele Perl- in JavaScript-Datenstruktur
444  
445 =head4 Synopsis
446  
447 $json = $j->encode($scalar);
448  
449 =head4 Arguments
450  
451 =over 4
452  
453 =item $scalar
454  
455 Skalarer Wert: undef, \0, \1, Number, String, String-Referenz,
456 Array-Referenz, Hash-Referenz.
457  
458 =back
459  
460 =head4 Returns
461  
462 JSON-Code (String)
463  
464 =head4 Description
465  
466 Wandele $scalar nach JSON und liefere den resultierenden Code zurück.
467 Die Übersetzung erfolgt (rekursiv) nach folgenden Regeln:
468  
469 =over 4
470  
471 =item undef
472  
473 Wird abgebildet auf: C<undefined>. In einem Objekt wird das
474 betreffende Attribut weggelassen.
475  
476 =item \1 oder \'true'
477  
478 Wird abgebildet auf: C<true>
479  
480 =item \0 oder \'false'
481  
482 Wird abgebildet auf: C<false>
483  
484 =item NUMBER
485  
486 Wird unverändert übernommen: NUMBER
487  
488 =item STRING
489  
490 Wird abgebildet auf: 'STRING'
491  
492 =item STRING_REF
493  
494 Wird abgebildet auf: STRING (literale Einsetzung von STRING)
495  
496 Dies ist z.B. nützlich, wenn ein Teil der Datenstruktur
497 abweichend formatiert werden soll.
498  
499 =item ARRAY_REF
500  
501 Wird abgebildet auf: [ELEMENT1,ELEMENT2,...]
502  
503 =item HASH_REF
504  
505 Wird abgebildet auf: {KEY1:VALUE1,KEY2:VALUE2,...}. Im Falle des
506 Werts undef, wird das betreffende Schlüssel/Wert-Paar weggelassen.
507  
508 =back
509  
510 =cut
511  
512 # -----------------------------------------------------------------------------
513  
514 1699 ▶sub encode {
Subroutine encode: called CC=14 SCAR=26.4
Pod documented
515 1699 my ($self,$arg) = @_;
516  
517 1699 my $json = '';
518  
519 1699 my $refType = Scalar::Util::reftype($arg);
520 1699 ▶ if (!defined $refType) {
Branch: 4 branches
BranchTrueFalseTotal
if (not defined $refType) { } 1585 114 1699
elsif ($refType eq 'SCALAR') { } 89 25 114
elsif ($refType eq 'ARRAY') { } 17 8 25
elsif ($refType eq 'HASH') { } 8 0 8
521 1585 ▶ if (!defined $arg) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $arg) { } 2 1583 1585
elsif (&Scalar::Util::looks_like_number($arg)) { } 1493 90 1583
522 2 $json = 'undefined';
523 }
524 elsif (Scalar::Util::looks_like_number($arg)) {
525 1493 $json = $arg;
526 }
527 else {
528 90 $json = "'$arg'";
529 }
530 }
531 elsif ($refType eq 'SCALAR') {
532 89 ▶ if ($$arg eq '1') {
Branch: 2 branches
BranchTrueFalseTotal
if ($$arg eq '1') { } 4 85 89
elsif ($$arg eq '0') { } 2 83 85
533 4 $json = 'true';
534 }
535 elsif ($$arg eq '0') {
536 2 $json = 'false';
537 }
538 else {
539 83 $json = $$arg;
540 }
541 }
542 elsif ($refType eq 'ARRAY') {
543 17 ▶ for (my $i = 0; $i < @$arg; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$arg) 1467 17 1484
544 1467 ▶ if ($json ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($json ne "") 1453 14 1467
545 1453 $json .= ',';
546 }
547 1467 $json .= $self->encode($arg->[$i]);
548 }
549 17 $json = "[$json]";
550 }
551 elsif ($refType eq 'HASH') {
552 8 for my $key (sort keys %$arg) {
553 14 ▶ my $val = $arg->{$key} // next; # Attribut streichen, wenn undef
Condition100%2/2
$arg->{$key} // (next)
l!l
131
MC/DC100%1/1
$arg->{$key} // (next)
$arg->{$key}
Truth table100%2/2
A
A= $arg->{$key}
Aresult
11
00
554 13 ▶ if ($json) {
Branch: 1 branch
BranchTrueFalseTotal
if ($json) 6 7 13
555 6 $json .= ',';
556 }
557 13 $json .= $self->key($key);
558 13 $json .= ':'.$self->encode($val);
559 }
560 8 $json = "{$json}";
561 }
562 else {
563 0 $self->throw(
564 'JSON-00001: Unknown data type',
565 Arg => $arg,
566 Type => $refType,
567 );
568 }
569  
570 1699 return $json;
571 }
572  
573 # -----------------------------------------------------------------------------
574  
575 =head3 object() - Erzeuge Code für JSON-Objekt
576  
577 =head4 Synopsis
578  
579 $json = $j->object(@opt,@keyVal); # Scalar-Kontext
580 ($jsonS) = $j->object(@opt,@keyVal); # List-Kontext
581  
582 =head4 Alias
583  
584 o()
585  
586 =head4 Arguments
587  
588 =over 4
589  
590 =item @keyVal
591  
592 Liste der Schlüssel/Wert-Paare
593  
594 =back
595  
596 =head4 Options
597  
598 =over 4
599  
600 =item -indent => $bool (Default: 1)
601  
602 Rücke die Elemente des Hash ein.
603  
604 =back
605  
606 =head4 Returns
607  
608 JSON-Code (String). Im List-Kontext eine Referenz auf den Code.
609  
610 =head4 Description
611  
612 Erzeuge den Code für ein JSON-Objekt mit den Attribut/Wert-Paaren
613 @keyVal und liefere diesen zurück.
614  
615 =cut
616  
617 # -----------------------------------------------------------------------------
618  
619 58 ▶sub object {
Subroutine object: called CC=14 SCAR=26.8
Pod documented
620 58 my $self = shift;
621 # @_: @keyVal
622  
623 # Optionen
624  
625 58 my $indent = 1;
626  
627 58 ▶ while (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 59 0 59
628 59 ▶ if (substr($_[0],0,1) ne '-') {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($_[0], 0, 1) ne "-") 58 1 59
629 # Implizites Ende der Optionsliste
630 58 last;
631 }
632 1 my $opt = shift;
633 1 ▶ if ($opt eq '-') {
Branch: 2 branches
BranchTrueFalseTotal
if ($opt eq '-') { } 0 1 1
elsif ($opt eq '-indent') { } 1 0 1
634 # Explizites Ende der Optionsliste
635 0 last;
636 }
637 elsif ($opt eq '-indent') {
638 1 $indent = shift;
639 }
640 else {
641 0 $self->throw(
642 'JSON-00001: Unknown option',
643 Option => $opt,
644 Value => shift,
645 );
646 }
647 }
648  
649 58 my $json = '';
650 58 ▶ if ($indent) {
Branch: 1 branch
BranchTrueFalseTotal
if ($indent) { } 57 1 58
651 57 ▶ while (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 215 57 272
652 215 my $key = shift;
653 215 ▶ my $val = shift // next;
Condition100%2/2
shift() // (next)
l!l
20510
MC/DC100%1/1
shift() // (next)
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
654 205 ▶ if ($json) {
Branch: 1 branch
BranchTrueFalseTotal
if ($json) 148 57 205
655 148 $json .= "\n";
656 }
657 205 $json .= sprintf '%s: %s,',$self->key($key),$self->encode($val);
658 }
659 57 ▶ if ($json) {
Branch: 1 branch
BranchTrueFalseTotal
if ($json) { } 57 0 57
660 57 my $indent = ' ' x $self->{'indent'};
661 57 $json =~ s/^/$indent/mg;
662 57 $json = "{\n$json\n}";
663 }
664 else {
665 0 $json = '{}';
666 }
667 }
668 else {
669 1 ▶ while (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 2 1 3
670 2 my $key = shift;
671 2 ▶ my $val = shift // next;
Condition50%1/2
shift() // (next)
l!l
20
MC/DC0%0/1
shift() // (next)
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
672 2 ▶ if ($json) {
Branch: 1 branch
BranchTrueFalseTotal
if ($json) 1 1 2
673 1 $json .= ',';
674 }
675 2 $json .= $self->key($key).':'.$self->encode($val);
676 }
677 1 $json = "{$json}";
678 }
679  
680 58 ▶ return wantarray? \$json: $json;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 47 11 58
681 }
682  
683 {
684 7 ▶ no warnings 'once';
Subroutine BEGIN: called CC=1 SCAR=0.0
685 7 *o = \&object;
686 }
687  
688 # -----------------------------------------------------------------------------
689  
690 =head2 Hilfsmethoden
691  
692 =head3 key() - Schlüssel eines JSON-Objekts
693  
694 =head4 Synopsis
695  
696 $str = $j->key($key);
697  
698 =head4 Arguments
699  
700 =over 4
701  
702 =item $key
703  
704 Schlüssel.
705  
706 =back
707  
708 =head4 Returns
709  
710 String
711  
712 =head4 Description
713  
714 Erzeuge den Code für den Schlüssel $key eines JSON-Objekts und
715 liefere diesen zurück. Enthält der Schlüssel nur Zeichen, die
716 in einem JavaScript-Bezeichner vorkommen dürfen, wird er unverändert
717 geliefert, ansonsten wird er in einfache Anführungsstriche eingefasst.
718  
719 =head4 Example
720  
721 Schlüssel aus dem Zeichenvorrat eines JavaScript-Bezeichners:
722  
723 $str = $j->Quiq::Json::Code('borderWidth');
724 ==>
725 "borderWidth"
726  
727 Schlüssel mit Zeichen, die nicht in einem JavaScript-Bezeichner vorkommen:
728  
729 $str = $j->Quiq::Json::Code('border-width');
730 ==>
731 "'border-width'"
732  
733 =cut
734  
735 # -----------------------------------------------------------------------------
736  
737 222 ▶sub key {
Subroutine key: called CC=2 SCAR=6.9
Pod documented
738 222 my ($self,$key) = @_;
739 222 ▶ return $key =~ /\W/? "'$key'": $key;
Branch: 1 branch
BranchTrueFalseTotal
$key =~ /\W/ ? : 1 221 222
740 }
741  
742 # -----------------------------------------------------------------------------
743  
744 =head1 VERSION
745  
746 1.240
747  
748 =head1 AUTHOR
749  
750 Frank Seitz, L<http://fseitz.de/>
751  
752 =head1 COPYRIGHT
753  
754 Copyright (C) 2026 Frank Seitz
755  
756 =head1 LICENSE
757  
758 This code is free software; you can redistribute it and/or modify
759 it under the same terms as Perl itself.
760  
761 =cut
762  
763 # -----------------------------------------------------------------------------
764  
765 7 1;
766  
767 # eof
« Quiq/Formatter.pm ↑ Summary Quiq/Html/Widget/CheckBoxBar.pm »