Search code examples
jsonperl

Parsing JSON says function parse_json does not exist?


The following code fails with an error saying that parse_json is undefined.

use strict;
use JSON::Parse;
my $x = "['a', 'b']";
my $json = parse_json($x);

But, this page claims it works: https://metacpan.org/pod/JSON::Parse

What am I doing wrong?


Solution

  • The documentation repeatedly uses

    use JSON::Parse 'parse_json';
    

    and

    use JSON::Parse ':all';
    

    while you used

    use JSON::Parse;
    

    While all three load the module, only the former two exports parse_json.

    I believe it's a good practice to list your imports even when you're not required as it makes it a whole lot easier to work with code down the line. This is not relevant with this module because listing the imports is required.