note
Loops
<p>You could use one of the JSON readers that have a streaming capability rather than loading the entire thing into memory, such as [metamod://JSON::Streaming::Reader]. The code below is a quick try that works here, although I don't have any multi-meg JSON files handy. Have to provide routines for each element type read in the stream; the code below just has null subs for them but doing a $jsonr->skip instead would probably speed things up even more:</p>
<c>
use IO::File;
use JSON::Streaming::Reader;
sub is_valid_json {
my $fh = IO::File->new(shift, "r");
my $jsonr = JSON::Streaming::Reader->for_stream($fh);
my @ignore = map {($_, sub {})}
qw(start_array end_array start_object add_string add_number
add_boolean add_null end_object start_property end_property);
eval {$jsonr->process_tokens(@ignore, error => sub {die "@_"})};
return !$@;
}
print is_valid_json('file.json') ? 'ok' : 'panic';
</c>
1108135
1108135