JSON-Builder

 view release on metacpan or  search on metacpan

JSON/Builder.pm  view on Meta::CPAN

=head1 NAME

JSON::Builder - to build large JSON with temp files when memory limit, and compress optionaly.

=head1 SYNOPSIS

 use JSON::Builder;
 
 my $json = JSON::XS->new()->utf8(1)->ascii(1);
 my ($fh, $filename) = tempfile();
 unlink $filename;
 
 my $builder = JSON::Builder->new(json => $json, fh => $fh);
 or
 my $builder = JSON::Builder::Compress->new(json => $json, fh => $fh); # Compress, Base64
  
 my $fv = $builder->val( { a => 'b', c => 'd' } );
 
 my $l = $builder->list();
 $l->add( { 1 => 'a', 2 => 'b' } );
 $l->add( { 1 => 'c', 2 => 'd' } );
 my $fl = $l->end();
 
 my $o = $builder->obj();
 $o->add( o1 => ['a', 'b'] );
 $o->add( o2 => ['c', 'd'] );
 my $fo = $o->end();
 
 my %d = (
 	one => 1,
 	v   => $fv,
 	l   => $fl,
 	o   => $fo,
 );
 
 $builder->encode(\%d);
 
 # print for test
 $fh->flush();
 $fh->seek(0,0);
 print <$fh>;

=head1 MOTIVATION

Task: to create JSON while having the memory limitations.

If you have only one large value in JSON, or, large values are created one by one, you can use the streaming generator. Otherwise, you should use such a perl structure where large elements are the filehandle with the json fragments. When a perl struc...

=head1 DESCRIPTION

=head2 JSON::Builder

=head3 new

The constructor accepts the following arguments:

=over

=item json

JSON object with the encode and allow_nonref methods support, e.g. JSON::XS.

=item fh

The filehandle of the file where the result should be written into.

=item read_in

LENGTH of L<read> function. Optional.

=back

 my $builder = JSON::Builder->new(json => $json, fh => $fh);

=head3 val

It turns the data to JSON, saves JSON into the variable file created and returns the filehandle of this temporary file:

 my $fv = $builder->val( { a => 'b', c => 'd' } );

=head3 list

Its returns the object JSON::Builder::List

=head3 obj

Its returns the object JSON::Builder::Obj

=head3 encode

Turns the passed data structure into JSON.

 my %d = (
 	one => 1,
 	v   => $fv, # file handler if $builder->val(...)
 	l   => $fl, # file handler of JSON::Builder::List
 	o   => $fo, # file handler of JSON::Builder::Obj
 );

 $builder->encode(\%d)

=head2 JSON::Builder::List

It is aimed to write the JSON elements list into the temporary file.

 my $l = $builder->list();
 $l->add( { 1 => 'a', 2 => 'b' } );



( run in 0.495 second using v1.01-cache-2.11-cpan-39bf76dae61 )