Am I missing anything, or does JSON lacks a write_to_file()
and read_from_file()
s开发者_开发技巧ubroutines?
Obviously, I can easily implement them, but as they seem so handy I wonder how can it be they are not there.
Yeah, it lacks a write_to_file()
and read_from_file()
function because usually, you don't store JSON in files but use it only to send data back to the web client. You've got to implement it by yourself, which, as you said correctly, isn't that much to do.
use JSON;
sub read_from_file {
my $json;
{
local $/; #Enable 'slurp' mode
open my $fh, "<", "data_in.json";
$json = <$fh>;
close $fh;
}
return decode_json($json);
}
sub write_to_file {
my $data = shift;
open my $fh, ">", "data_out.json";
print $fh encode_json($data);
close $fh;
}
精彩评论