What is the to_json method in Mojo::JSON?

Overview

The to_json method is used to encode the Perl value to JSON without UTF-8 encoding it. This method is provided by the module Mojo::JSON, which provides methods to manipulate JSON.

Syntax

to_json $hash

Where the hash is the Perl value.

Return value

The to_json method returns a JSON text.

Let's take a look at an example.

Example

In the following example, we'll try to encode a Perl value without UTF-8 encoding it, and print the returned JSON text.

# import required packages
use 5.010;
use Data::Dumper;
use Mojo::JSON qw(to_json);
# given Perl value
my $hash = {
comment => 'I ♥ Educative'
};
# encode the given Perl value
my $json = to_json $hash;
# Print the returned JSON
say $json

Explanation

In the code snippet above:

  • Line 7: We declare and initialize the Perl hash which we want to convert to JSON.
  • Line 13: We encode the given Perl value hash into JSON without UTF-8 encoding it using the method to_json.
  • Line 16: We print the returned json.

Free Resources