首页 > 解决方案 > Comparing json files of array of nested hash in perl

问题描述

I have 2 JSON files file1.json and file2.json. I want to compare the contents in it in Perl Language


file1.json

   [{
     "id": 12036289,
     "name": "DEFAULT ADMIN",
     "email": "admin@saurabh.com",
     "groups": [{
        "id": 12036287,
        "name": "Service Admin"
     }],
     "department": {
         "id": 12036288,
         "name": "Service Admin"
     },
     "adminUser": true
  }, {
     "id": 12046238,
     "name": "saurabh",
     "email": 
     "vbdfuyqwvbvvbduiqwvbduyvbqwuidvbq@saurabh.com",
     "groups": [{
         "id": 12046237,
         "name": "uiwgbfuisaufusgafuuuuuuuuuuuuugsdaaaaaaiqd"
     }],
     "department": {
        "id": 12046236,
        "name": "uiwvbdusguuuuuuuuuuuuuuugsdaaaaaaiuad2"
     },
     "adminUser": false
  }]

file2.json

 [{
    "id": 12046238,
    "name": "saurabh",
    "email": 
    "vbdfuyqwvbvvbduiqwvbduyvbqwuidvbq@saurabh.com",
    "groups": [{
       "id": 12046237,
       "name": "uiwgbfuisaufusgafuuuuuuuuuuuuugsdaaaaaaiqd"
    }],
    "department": {
       "id": 12046236,
       "name": "uiwvbdusguuuuuuuuuuuuuuugsdaaaaaaiuad2"
    },
    "adminUser": false
 }, {
   "id": 12036289,
   "name": "DEFAULT ADMIN",
   "email": "admin@saurabh.com",
   "groups": [{
       "id": 12036287,
       "name": "Service Admin"
    }],
    "adminUser": true,
    "department": {
       "id": 12036288,
       "name": "Service Admin"
     }
 }]

Here the contents are not in order but same. What i tried was to decode the json file and compare the arrays using cmp_deeply() function. But i was not able to do that. Do anyone have some approach to this problem?


EDIT   code supplied in a comment

use strict; 
use warnings;
use JSON;
use Test::Deep;

my $file1;
#slurp mode 
{ 
    open(FILE,'<','file1.json');
    local $/ = undef;
    $file1 = <FILE>;
}

my $file2;
#slurp mode
{ 
    open(FILE,'<','file2.json');
    local $/ = undef;
    $file2 = <FILE>;
}

my @array1 = @{decode_json $file1};
my @array2 = @{decode_json $file2};
print @array1;

print cmp_deeply( @array1, @array2 );

标签: jsonperl

解决方案


my @array1 = @{decode_json $file1};
my @array2 = @{decode_json $file2};
print cmp_deeply( @array1, @array2 );

应该

my @array1 = @{decode_json $file1};
my @array2 = @{decode_json $file2};
print cmp_deeply( \@array1, \@array2 );

避免无用的复制会更好。

my $array1 = decode_json $file1;
my $array2 = decode_json $file2;
print cmp_deeply( $array1, $array2 );

推荐阅读