JSON::XS “Usage” croak

删除回忆录丶 提交于 2019-12-10 14:18:20

问题


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?


回答1:


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"
                              | # ]


来源:https://stackoverflow.com/questions/14291605/jsonxs-usage-croak

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!