| 1 | ##-*- Mode: CPerl -*- | ||
| 2 | |||
| 3 | ## File: DDC::Format::JSON.pm | ||
| 4 | ## Author: Bryan Jurish <moocow@cpan.org> | ||
| 5 | ## Description: | ||
| 6 | ## + DDC Query utilities: output formatting: Data::Dumper | ||
| 7 | ##====================================================================== | ||
| 8 | |||
| 9 | package DDC::Format::JSON; | ||
| 10 | use JSON; | ||
| 11 | use Carp; | ||
| 12 | use strict; | ||
| 13 | |||
| 14 | ##====================================================================== | ||
| 15 | ## Globals | ||
| 16 | our @ISA = qw(DDC::Format); | ||
| 17 | |||
| 18 | ##====================================================================== | ||
| 19 | ## Constructors, etc. | ||
| 20 | |||
| 21 | ## $fmt = $CLASS_OR_OBJ->new(%args) | ||
| 22 | ## + %args: | ||
| 23 | ## ( | ||
| 24 | ## pretty => $level, ##-- json prettification level (default:0) | ||
| 25 | ## jxs => $jxs, ##-- underlying JSON object | ||
| 26 | ## ) | ||
| 27 | sub new { | ||
| 28 | my $that = shift; | ||
| 29 | my $fmt = bless { | ||
| 30 | level=>0, | ||
| 31 | jxs =>JSON->new->utf8(1)->relaxed(1)->canonical(0)->allow_blessed(1)->convert_blessed(1), | ||
| 32 | @_ | ||
| 33 | }, ref($that)||$that; | ||
| 34 | return $fmt; | ||
| 35 | } | ||
| 36 | |||
| 37 | ## $fmt = $fmt->reset() | ||
| 38 | ## + reset counters, etc. | ||
| 39 | sub reset { | ||
| 40 | $_[0]{jxs}->pretty($_[0]{level}||0); | ||
| 41 | $_[0]{jxs}->canonical(abs($_[0]{level}||0)>1 ? 1 : 0); | ||
| 42 | return $_[0]->SUPER::reset(); | ||
| 43 | } | ||
| 44 | |||
| 45 | ##====================================================================== | ||
| 46 | ## Helper functions | ||
| 47 | |||
| 48 | ## $hitStr = $fmt->hitString($hit) | ||
| 49 | ## + increments $fmt->{start} | ||
| 50 | sub hitString { | ||
| 51 | my ($fmt,$hit) = @_; | ||
| 52 | return $fmt->{jxs}->pretty($_[0]{level}||0)->canonical(abs($_[0]{level}||0)>1 ? 1 : 0)->encode($hit); | ||
| 53 | } | ||
| 54 | |||
| 55 | ##====================================================================== | ||
| 56 | ## API | ||
| 57 | |||
| 58 | ## $str = $fmt->toString($hitList) | ||
| 59 | sub toString { | ||
| 60 | my ($fmt,$hits) = @_; | ||
| 61 | return $fmt->{jxs}->pretty($_[0]{level}||0)->canonical(abs($_[0]{level}||0)>1 ? 1 : 0)->encode($hits); | ||
| 62 | } | ||
| 63 | |||
| 64 | 1; ##-- be happy | ||
| 65 | |||
| 66 | __END__ |