Why doesn't the Perl JSON module read and write files?

Am I missing anything or is JSON missing routines write_to_file()and read_from_file()?

Obviously, I can easily implement them, but since they seem so convenient, I wonder how it can be, they do not exist.

+3
source share
2 answers

Yes, it lacks a function write_to_file()and read_from_file(), because usually you do not store JSON in files, but use it only to send data back to the web client. You must implement it yourself, which, as you said correctly, is not so much.

+8
source
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;
}
+6
source

Source: https://habr.com/ru/post/1771278/


All Articles