$YAML::XS::Boolean
=
'JSON::PP'
;
our
@EXPORT
=
qw(read_json read_yaml io_yaml_or_json write_json write_yaml)
;
sub
read_json {
my
$str
= path(
shift
)->slurp_utf8;
return
decode_json(
$str
);
}
sub
read_yaml {
my
$data
= LoadFile(
shift
);
traverse_yaml_data_to_coerce_numbers(
$data
)
;
return
$data
;
}
sub
io_yaml_or_json {
my
$arg
=
shift
;
my
$file
=
$arg
->{filepath};
my
$mode
=
$arg
->{mode};
my
$data
=
$mode
eq
'write'
?
$arg
->{data} :
undef
;
my
@exts
=
qw(.yaml .yml .json .jsonld .ymlld .yamlld)
;
my
$msg
=
qq(Can't recognize <$file> extension. Extensions allowed are: )
. (
join
','
,
@exts
) .
"\n"
;
my
(
undef
,
undef
,
$ext
) = fileparse(
$file
,
@exts
);
die
$msg
unless
any {
$_
eq
$ext
}
@exts
;
$ext
=~
tr
/a.//d;
$ext
=~ s/ld$//;
my
$return
= {
read
=> {
json
=> \
&read_json
,
yml
=> \
&read_yaml
},
write
=> {
json
=> \
&write_json
,
yml
=> \
&write_yaml
}
};
return
$mode
eq
'read'
?
$return
->{
$mode
}{
$ext
}->(
$file
)
:
$return
->{
$mode
}{
$ext
}->( {
filepath
=>
$file
,
data
=>
$data
} );
}
sub
write_json {
my
$arg
=
shift
;
my
$file
=
$arg
->{filepath};
my
$json_data
=
$arg
->{data};
my
$json
=
JSON::XS->new->utf8->canonical->pretty->encode(
$json_data
);
path(
$file
)->spew(
$json
);
return
1;
}
sub
write_yaml {
my
$arg
=
shift
;
my
$file
=
$arg
->{filepath};
my
$json_data
=
$arg
->{data};
DumpFile(
$file
,
$json_data
);
return
1;
}
sub
traverse_yaml_data_to_coerce_numbers {
my
$data
=
shift
;
my
$walker
= Data::Leaf::Walker->new(
$data
);
while
(
my
(
$key_path
,
$value
) =
$walker
->
each
) {
$walker
->store(
$key_path
,
$value
+ 0 )
if
Scalar::Util::looks_like_number
$value
;
}
}
1;