FreeKB - Reading a JSON file using JSON::Parse in Perl - Getting Started
Reading a JSON file using JSON::Parse in Perl - Getting Started

Home > Search


Let's say you have example.json that contains the following markup.

[
 {"foo":"bar"}
]

 

The JSON::Parse module can be used to extract the key (foo) and value (bar) from example.json.

use JSON::Parse 'json_file_to_perl';

 

You would then use the json_file_to_perl function to read example.json and to store the result in a variable.

my $jsonHash = json_file_to_perl ('example.json');

 

You can now print the variable.

print $jsonHash

 

Either ARRAY or HASH should be printed.

ARRAY

 

Or, you can print the variable to dumper to validate that the JSON file is being parsed properly.

print Dumper $jsonHash

 

Dumper should produce the following.

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

 

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

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

  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 e5d83 in the box below so that we can be sure you are a human.




Comments