使用解析器,不要试图重新发明轮子。这是一个例子:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON qw( decode_json encode_json );
my $data = { foo => 'bar', baz => [1,2,3], qux => { abc => 1, def => 2, ghi => 3} };
my $json = encode_json($data);
my $error_json = $json;
$error_json =~ s|\]||; # Remove a closing square bracket
eval {
my $error_data = decode_json($error_json); # Will throw an error
};
my $error = $@;
if ($error) {
print "JSON Error : $error";
my ($char_pos) = $error =~ m|at character offset (\d+)|;
print "Original : '$json'\n";
print "Error : '$error_json'\n";
print "..............";
print "."x($char_pos) . "^\n";
} else {
die "should not get here...something went wrong";
}
输出
JSON Error : , or ] expected while parsing array, at character offset 31 (before ":{"abc":1,"ghi":3,"d...") at foo.pl line 15.
Original : '{"foo":"bar","baz":[1,2,3],"qux":{"abc":1,"ghi":3,"def":2}}'
Error : '{"foo":"bar","baz":[1,2,3,"qux":{"abc":1,"ghi":3,"def":2}}'
.............................................^