You could use one of the JSON readers that have a streaming capability rather than loading the entire thing into memory, such as 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:
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';
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|