NAME
Mojo::File::Role::JSON - Adds a json method to Mojo::File to store and retrieve JSON
SYNOPSIS
use Mojo::File qw/path/;
my $file = path("data.json")->with_roles('+JSON');
# Store JSON
$file->json({foo => "bar"});
# Retrieve JSON
my $data = $file->json;
# Store with pretty formatting
$file->pretty(1)->json({foo => "bar"});
# Merge new data into the existing file
$file->merge({baz => 42});
# Run transformation on existing JSON
$file->do(sub { $_->{hello} = "world" });
DESCRIPTION
This role adds JSON serialization methods to Mojo::File objects, allowing them to easily store and retrieve JSON data. It also includes support for merging and updating JSON content, and optional pretty-printing.
METHODS
json
$file->json({ foo => "bar" }); # stores a variable as JSON in the file
my $data = $file->json(); # retrieves the decoded JSON from the file
Stores or retrieves JSON data from the file.
When called with an argument, encodes it as JSON and writes it to the file. If the file's parent directory does not exist, it will be created.
Returns the deserialized data structure when reading.
If called in object context during storage (e.g. `$file->json(...)`), returns the object.
Returns undef if the file does not exist when reading.
store
$file->store($data);
Stores the given data structure as JSON into the file. Alias for json()
in write mode.
Dies if no data is passed.
retrieve
my $data = $file->retrieve;
Retrieves and returns the JSON content of the file.
Alias for json()
in read mode.
pretty
$file->pretty(1);
Enables or disables pretty-printed JSON when writing.
Returns the file object itself.
policy
$file->policy("die");
Sets the policy for file-not-found handling.
Note: Currently unused, reserved for future use.
merge
$file->merge({ bar => 42 });
Merges the provided hash into the current JSON structure in the file and stores the result.
Uses Hash::Merge for merging.
do
$file->do(sub { $_->{count}++ });
Executes a subroutine on the current JSON content.
The sub receives the data structure in $_
, and its return value is stored back in the file.
SEE ALSO
Mojo::File, JSON::MaybeXS, Hash::Merge, Want
AUTHOR
Simone Cesano
This software is copyright (c) 2025 by Simone Cesano.
COPYRIGHT AND LICENSE
This software is copyright (c) 2025 by Simone Cesano.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.