我将数据转换为json时遇到问题,我不知道为什么。
这是一些有效的代码:
#constructor
sub new {
my $class = shift;
my $Titel = shift;
my $Text = shift;
my $Time = localtime;
my $self = {};
$self->{text} = $Text;
$self->{create} = $Time;
$self->{edit} = $Time;
my $json = JSON::XS->new();
open WF, '>> $file' || die "Error : $!";
print WF $json->encode($self)."\n";
close WF;
bless $self, $class;
}
我也创建了一个“对象”,并将数据保存在文本文件中(通过JSON)。
如果尝试编辑一些数据,我会遇到问题:
sub edit {
my $self = shift;
my $Text = shift;
my $ID = shift;
my $Time = localtime;
my $json = JSON::XS->new();
$json->allow_blessed(1);
$self->{text} = $Text; #edit text
$self->{edit} = $Time; # edit date
open INPUT, '< $file' || die "Error : $!";
my @data = <INPUT>;
close(INPUT);
open WF, '> $file' || die "Error : $!";
for (my $Count=0; $Count<=$#data; $Count++){
chomp($data[$Count]);
if($Count == $ID){#if line of data found, who is going to be edited
print WF $json->encode($self)."\n";
}else{
print WF $data[$Count]."\n";
}
}
close WF;
}
我想做的是只编辑文本文件中的一行。.(如果您有更好的主意,请告诉我:D)
我看到我的程序在第一个显示的代码和那个代码之间没有区别。
它只是在文本文件中写回“ null” ...
有任何想法吗?
最佳答案
我不是JSON专家,但是encode
方法遇到了引用错误的麻烦。使用无偏的引用似乎是一种有效的解决方法:
if($Count == $ID){#if line of data found, who is going to be edited
print WF $json->encode( {%$self} )."\n";
...
关于json - Perl将数据转换为JSON格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5782441/