Search code examples
jsonperleval

Perl how can I check if json file is empty, invalid and correct


I want to check 3 cases regarding JSON files

  1. The JSON file is correct
  2. The JSON file is completely empty
  3. The JSON file is invalid

In order to illustrate those, here 3 samples

  1. JSON file is correct
{
   "menu":{
      "id":"file",
      "popup":{
         "menuitem":[
            
         ]
      }
   }
}
  1. JSON file is empty
[ ]
  1. JSON file is invalid
[ i ]

I tried to manage the scenario 1. and 3. I guess, but I can't find a way to process the scenario 2. so I need your hints on this.

#!/usr/bin/perl
use strict;
use warnings;
use JSON qw( decode_json );
use JSON qw( from_json );

# JSON file 
my $json_f = '/home/test.json';

# JSON text
my $json_text = do {
        open (TOP, "<", $json_f);
        local $/;
        <TOP>
};

my $data = from_json($json_text);

my $json_out = eval { decode_json($json_text) };
if ($@) {
    print "JSON file is invalid :$@\n";
} else {
        print "JSON file is correct", "\n";
}

Solution

  • I think I'd probably do something like this:

    • does the file exist? -e $file
    • if the file exists, does it have content? -s $file (0 means zero bytes). You can also look at the content you read: length($data) == 0.
    • if it has content, is it valid JSON? Use the stuff you already have.

    But, it seems like you have another case where you have valid JSON but the array or objects have no values. That's perfectly valid so you get another step. You either have a value, an array, or an object. Check each type; if it's an array or object, check that it has elements or keys.