[英]Why does Perl's JSON module not read or write files?
Am I missing anything, or does JSON lacks a write_to_file()
and read_from_file()
subroutines? 我错过了什么,或者JSON缺少write_to_file()
和read_from_file()
子例程吗?
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. 是的,它缺少write_to_file()
和read_from_file()
函数,因为通常,您不会将JSON存储在文件中,而只是将其用于将数据发送回Web客户端。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.