Perl将数据转换为JSON格式

时间:2011-04-25 19:42:35

标签: 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”...

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

我不是JSON专家,但是encode方法在使用祝福参考时遇到了问题。使用未经证实的引用似乎是一种有效的解决方法:

if($Count == $ID){#if line of data found, who is going to be edited
    print WF $json->encode( {%$self} )."\n";
...

答案 1 :(得分:1)

我的第二个概念(正如你已经发现的那样)问题是受祝福的引用,但是我提供了另一个解决方案(毕竟是Perl:TIMTOWTDI)。 Acme::Damn模块允许您取消(即该死)一个对象。因此,你应该能够:

print WF $json->encode(damn($self))."\n";

此外,我觉得我必须分享,因为这个方法非常巧妙。

答案 2 :(得分:-1)

按照最后一个小怪的建议,这里有一个简单的例子,如何序列化有福的参考文献。

package Node;

sub new {
    my $class = shift;
    bless { @_ }, $class;
}

sub TO_JSON {
    my $self = shift;
    return { class => 'Node', data => { %$self } };
}

package main;

use JSON;

my $node_hash = {
    a => [ 'text1', 'text2' ],
    b => [ 'what',  'is', 'this' ],
    c => [ Node->new(some => 'data') ],
};

print to_json($node_hash, { convert_blessed => 1 });

但是你需要注意解码。可以使用filter_json_single_key_object来实现完整的往返。

相关问题