6

I can't seem to use JSON::XS's OO interface properly. The following croaks with an error I can't track down:

use JSON::XS;
my $array = ['foo', 'bar'];

my $coder = JSON::XS->new->utf8->pretty;
print $coder->encode_json($array);

This croaks with the following: Usage: JSON::XS::encode_json(scalar) at test.pl line 5. I have been combing through the code for JSON::XS and I can't find a "Usage:" warning anywhere. My usage seems to be pretty well matched with the examples in the documentation. Can anyone tell me where I have gone wrong?

Nate Glenn
  • 6,455
  • 8
  • 52
  • 95

1 Answers1

11

JSON::XS has two interfaces: functional and OO.

  • In the functional interface, the function name is encode_json.
  • In the OO interface, the method is simply encode, not encode_json.

Both of the following two snippets work:

# Functional                  | # OO
------------------------------+-----------------------------------------
                              | 
use JSON::XS;                 | use JSON::XS;
my $array = ['foo', 'bar'];   | my $array = [ 'foo', 'bar' ];
                              |
print encode_json($array);    | my $coder = JSON::XS->new->utf8->pretty;
                              | print $coder->encode($array);
                              |
# ["foo","bar"]               | # [
                              | #    "foo",
                              | #    "bar"
                              | # ]
Zaid
  • 36,680
  • 16
  • 86
  • 155