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 packagesuse 5.010;use Data::Dumper;use Mojo::JSON qw(to_json);# given Perl valuemy $hash = {comment => 'I ♥ Educative'};# encode the given Perl valuemy $json = to_json $hash;# Print the returned JSONsay $json
Explanation
In the code snippet above:
- Line 7: We declare and initialize the Perl
hashwhich we want to convert to JSON. - Line 13: We encode the given Perl value
hashinto JSON without UTF-8 encoding it using the methodto_json. - Line 16: We print the returned
json.