json - Perl将数据转换为JSON格式

标签 json perl

我将数据转换为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/

相关文章:

php - Android MySql 使用 php 创建图像并将其上传到服务器

ios - 如何从具有多个数组和括号的大型 JSON 响应中获取值?

bash - 正则表达式 : why can't I use a capture group inside curly braces {}

perl - 如何使用 Perl SOAP::Lite 将文件从本地计算机上传到 Sharepoint?

perl - 为什么在 mod_perl 中加载我的 Perl 模块会导致 Apache 挂起?

php - 如何将项目添加到json文件格式的数组

javascript - 我怎么能从 JSON 中获取我的标题,但无法获取我的练习词

JSON Serde - 映射列名

perl - Perl 脚本可以修改自身吗?

html - 如何获取 Excel 中的链接以在单个浏览器选项卡中打开