我正在尝试使用JSON来保存和读取配置文件。我想在配置文件中选择使用注释。对于常规Perl注释,注释行应以井号#
开头。
读取配置文件没问题,但是当我想在磁盘上回写时,所有注释都会丢失。例如:
use feature qw(say);
use strict;
use warnings;
use Data::Dump;
use JSON::XS;
my $json = JSON::XS->new->relaxed->pretty->canonical;
my $str = '
{
# Here we assign a value of 1 to a
"a" : 1,
"b" : {
"c" : 3, # and c should be equal to 3
"d" : 4
}
}
';
my $h = $json->decode($str);
#say $str;
#dd $h;
$h->{b}{a} = 2;
my $new_str = $json->encode($h);
say $new_str;
输出结果为:
{
"a" : "1",
"b" : {
"a" : 2,
"c" : "3",
"d" : "4"
}
}
而预期的输出是:
{
# Here we assign a value of 1 to a
"a" : 1,
"b" : {
"a" : 2,
"c" : 3, # and c should be equal to 3
"d" : 4
}
}
是否可以使用JSON实现,还是有其他更适合的配置文件格式?
答案 0 :(得分:1)
根据Wikipedia," JSON不提供或允许任何类型的评论语法。"
也许您可以在数据中允许注释节点。类似的东西:
{
"comment" : "# Here we assign a value of 1 to a",
"a" : 1,
"b" : {
"a" : 2,
"c" : 3, "comment" : "# and c should be equal to 3",
"d" : 4
}
}
答案 1 :(得分:1)