FreeKB - Getting Started with JSON::Parse
Perl - Getting Started with JSON::Parse

The JSON::Parse module can be used to parse a json file. Often, this is used with json_file_to_perl to read from a json file.

use JSON::Parse 'json_file_to_perl';

 

In this example, foo.json will be stored in a variable named $raw_json.

my $raw_json = json_file_to_perl ('foo.json');

 

Attempting to print the variable . . .

print $raw_json;

 

... with print either ARRAY ...

ARRAY

 

... or HASH.

HASH

 

Dumper can be used to print the raw json.

use Data::Dumper;
print Dumper $raw_json;

 

Dumper should produce something like this. There are no [ ] brackets, thus it's a hash.

$VAR1 = { 
          'foo' ==> 'bar'
        };

 

Or like this. There are [ ] brackets, thus it's an array.

$VAR1 = [
          { 
            'foo' ==> 'bar'
          }
        ];

 

If it's a hash, the following will print the value in the foo key.

print $raw_json->{'foo'};

 

Which should print bar.

bar

 

If it's an array, the following will print the value in the foo key.

foreach my $line (@{$raw_json}) {
  print $line->{'foo'};
}

 

Which should print bar.

bar

 

You can then loop through each key/value pair in the JSON file and print each key.

foreach my $line (@{$raw_json}) {

  foreach my $key (keys(%{$line})) {
    print $key;
  }

  foreach my $value (values(%{$line})) {
    print $value;
  }

}

 

The print $key line will print each key, which is just "foo" in this example.

foo

 

The print $value line will print each value, which is just "bar" in this example.

bar

 

Instead of looping through each value, you can just get the value from the key.

foreach my $line (@{$jsonHash}) {

  foreach my $key (keys(%{$line})) {
    print $key;
  }

  my $value = $key->{"foo"};
  print $value;

}

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter e2e0e in the box below so that we can be sure you are a human.




Comments