What is the encode_json method in Mojo::JSON?

Overview

The encode_json method is used to encode a Perl value to JSON. This method is provided by the Mojo::JSON module, which provides methods to manipulate JSON.

Syntax

encode_json $hash

Where the hash is the Perl value.

Return value

The encode_json method returns a JSON.

Let's look at an example of this method.

Example

In the following example, we will try to encode the Perl value and print the returned JSON.

# import required packages
use 5.010;
use Data::Dumper;
use Mojo::JSON qw(encode_json);
# given Perl value
my $hash = {
scores => [40,90],
name => 'John'
};
# encode the given Perl value
my $json = encode_json $hash;
# Print the returned JSON
say $json

Explanation

  • Line 7: We declare and initialize the Perl hash that we want to convert to JSON.
  • Line 13: We encode the given Perl value hash to JSON.
  • Line 16: We print the returned json.

Free Resources