What is the decode_json method in Mojo::JSON?

Overview

The decode_json method is used to decode JSON to Perl value. This method is provided by the module Mojo::JSON which provides methods to manipulate JSON.

Syntax

decode_json $json;

Where $json is the JSON string.

Return value

The method returns a Perl hash.

Example

In the following example, we will try to decode the JSON string and print the returned Perl hash.

# import required packages
use 5.010;
use Data::Dumper;
use Mojo::JSON qw(decode_json);
# given json string
my $json = '{"name":"John","scores":[40,90]}';
# decode the given json
my $hash = decode_json $json;
# Print the returned hash
print Dumper($hash);

Explanation

In the above code snippet,

  • Line 7: We declare and initialize the JSON string json.
  • Line 10: We decode the JSON string, json, using the decode_json method, and store it in the hash variable.
  • Line 13: We print the contents of the hash using the Dumper function, provided by the Data::Dumper module.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources