chandantul:
If you've got one JSON entry per line and are using the JSON package from cpan.org, then you'd handle the exception something like this:
use warnings;
use strict;
use JSON;
. . .
# Build a JSON parser
my $json = JSON->new->allow_nonref;
# Process the lines in the file, we're labelling the WHILE loop to mak
+e it obvious
# where we skip to after handling the exception
JSON_RECORD:
while (my $line = <INFILE>) {
# We'll declare the variable so we can use it outside of the eval
my $data;
# Parse the data inside the eval so we can catch the error
eval {
$data = $json->decode($line);
};
# Now we can check $@ to see if we had an exception
if ($@) {
# parse failed, so log it and let the user know
print "JSON parse failed on line $.\n";
print "error was: $@\n";
print "JSON we tried to parse <<$line>>\n\n";
# Now that we've handled the exception, skip to the next recor
next JSON_RECORD;
}
# OK if we get here, we've successfully parse the JSON data, so we
+ can do what
# we normally do now.
. . .
}
...roboticus
When your only tool is a hammer, all problems look like your thumb.
-
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.
|