sevarg24
sevarg24

Reputation: 3

Need to add new data to JSON array in perl

I'm trying to create a subroutine to append new values to a json file, but can't seem to put things together correctly. Eventually I would like to be able to plot this data. ideally, each time this routine is run, the newest data passed as an argument is added to the array so it can be plotted.

Here's what I've got so far.

# Subroutine to push CPU data to customer/device json file
sub push_json_data 
{
    my $json = JSON->new;
    #get these as arguements
    my $json_cpu_user = $_[0];
    my $json_cpu_system = $_[1];
    my $json_cpu_idle = $_[2];

    my $filename = 'data/custid_devid.json';
    #open file for read/write results
    #open (JSONFILE, "+>$filename");
    #print JSONFILE "$json_data";
    #close (JSONFILE);

    {
        local $/;  #Enable 'slurp' mode
        open my $fh, "<", "$filename";
        $json = <$fh>;
        close $fh;
    }

    my $data = decode_json($json);
    my $newdata = {user=>"$json_cpu_user",system=>"$json_cpu_system",idle=>"$json_cpu_idle"};

    my $previousdata = $data->{'CPU'};
    my $newjsondata = {"CPU"=>[$previousdata,$newdata]};
    print Dumper $newjsondata;

    open my $fh, ">", "data/custid_devid.json";
    print $fh encode_json($newjsondata);
    close $fh;
};

That outputs something like this...

$VAR1 = {
          'CPU' => [
                     [
                       [
                         {
                           'system' => '0',
                           'user' => '1',
                           'idle' => '97'
                         }
                       ],
                       {
                         'system' => '0',
                         'user' => '0',
                         'idle' => '98'
                       }
                     ],
                     {
                       'system' => '0',
                       'user' => '0',
                       'idle' => '98'
                     }
                   ]
        };

I'm getting the extra array for each value, how can I get around that?

Upvotes: 0

Views: 3621

Answers (1)

ysth
ysth

Reputation: 98528

If I start with a file like:

{"CPU":[]}

and modify your code to do:

my $newdata = {user=>"$json_cpu_user",system=>"$json_cpu_system",idle=>"$json_cpu_idle"};
my $data = decode_json($json);
push @{ $data->{'CPU'} }, $newdata;
...
print $fh encode_json($data);

it does what I think you want.

Upvotes: 3

Related Questions