Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl to convert data into JSON format

Tags:

json

perl

I have a problem, converting my data into json, and I don't know why.

Here is some Code that works:

#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;
}

I create an 'object' and save the data in a textfile (via JSON), too.

I have problems, if I try to edit some data:

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;
}

What I try to do is to edit just one line in the textfile.. (if you have a better idea, please show me :D)

I see no difference between my procedure in the code shown first and that one....

it just writes "null" back in the textfile...

Any ideas?

like image 407
Prexx Avatar asked Aug 28 '26 11:08

Prexx


2 Answers

I'm no JSON expert, but the encode method is having trouble with a blessed reference. Using an unblessed reference seems like a valid workaround:

if($Count == $ID){#if line of data found, who is going to be edited
    print WF $json->encode( {%$self} )."\n";
...
like image 82
mob Avatar answered Aug 31 '26 14:08

mob


I second the notion (as you have already found) that the problem is the blessed reference, however I offer you another solution (the is Perl after all: TIMTOWTDI). The Acme::Damn module allows you to unbless (i.e. damn) an object. Therefore you should be able to:

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

Also I felt I had to share, since the method is so cleverly named.

like image 44
Joel Berger Avatar answered Aug 31 '26 16:08

Joel Berger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!