Those 'JSONS' are not so 'JSONS' rather they just the hashes I inserted into a file with the following code:$VAR1 = { 'data' => { 'dir1' => { 'fileA' => { 'pid' => { '61781' => 1 }, 'total' => 13 }, 'fileB' => { 'pid' => { '61799' => 1 }, 'total' => 12 } } 'dir2' => { 'fileC' => { 'pid' => { '12345' => 1 }, 'total' => 10 }, 'fileA' => { 'pid' => { '61439' => 1 }, 'total' => 5 } } }, 'total' => { 'fileA' => 18, 'fileB' => 12 'fileC' => 10 } };
I use the following sub in order to decode each json:sub encode { my ($path,$href) = @_; my @json_arr = JSON::PP->new->encode($href); return convert_file_to_arr($path,@json_arr); }
Also, the sub which I iterate through the JSON files:sub decode { my ($path,$href) = @_; unless (-e $path) { return 0; } my ($json_data,@jarr); convert_file_to_arr($path,\@jarr); # inserts lines as elements of +array $json_data = (join "",@jarr); %{$href} = %{JSON::PP->new->decode($json_data)}; return 1; }
But of course it won't work, it been overridden every iteration and also it does not merge.sub merge_files_and_exec { my ($path,$list_of_dirs,$data_href) = @_; foreach my $dir (@{$list_of_dirs}) { decode($path,$data_href); } }
The merged hash should be;$VAR1 = { 'data' => { 'dir3' => { 'fileA' => { 'pid' => { '616161' => 1 }, 'total' => 6 }, 'fileD' => { 'pid' => { '54321' => 1 }, 'total' => 12 } } 'dir4' => { 'fileE' => { 'pid' => { '15151' => 1 }, 'total' => 3 }, 'fileA' => { 'pid' => { '1718' => 1 }, 'total' => 2 } } }, 'total' => { 'fileA' => 8, 'fileD' => 12 'fileE' => 3 } };
In the 'data' key we will add all the directories and their data. And in the 'total' section we will have all the files and their summed numbers.$VAR1 = { 'data' => { 'dir1' => { 'fileA' => { 'pid' => { '61781' => 1 }, 'total' => 13 }, 'fileB' => { 'pid' => { '61799' => 1 }, 'total' => 12 } } 'dir2' => { 'fileC' => { 'pid' => { '12345' => 1 }, 'total' => 10 }, 'fileA' => { 'pid' => { '61439' => 1 }, 'total' => 5 } } }, 'dir3' => { 'fileA' => { 'pid' => { '616161' => 1 }, 'total' => 6 }, 'fileD' => { 'pid' => { '54321' => 1 }, 'total' => 12 } } 'dir4' => { 'fileE' => { 'pid' => { '15151' => 1 }, 'total' => 3 }, 'fileA' => { 'pid' => { '1718' => 1 }, 'total' => 2 } } }, 'total' => { 'fileA' => 26, 'fileB' => 12 'fileC' => 10 'fileD' => 12 'fileE' => 3 } };
In reply to Merge hashes in specific format by ovedpo15
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |