我正在尝试创建一个子程序来将新值附加到json文件,但似乎无法正确地将它们放在一起。最终我希望能够绘制这些数据。理想情况下,每次运行此例程时,作为参数传递的最新数据都会添加到数组中,以便可以绘制它。
这是我到目前为止所得到的。
# 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;
};
输出这样的东西......
$VAR1 = {
'CPU' => [
[
[
{
'system' => '0',
'user' => '1',
'idle' => '97'
}
],
{
'system' => '0',
'user' => '0',
'idle' => '98'
}
],
{
'system' => '0',
'user' => '0',
'idle' => '98'
}
]
};
我为每个值获取了额外的数组,我该如何解决这个问题呢?
答案 0 :(得分:3)
如果我从以下文件开始:
{"CPU":[]}
并修改您的代码:
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);
它做了我认为你想要的。