Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON::XS "Usage" croak

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?

like image 522
Nate Glenn Avatar asked Jan 12 '13 08:01

Nate Glenn


People also ask

What is JSON and how is it used?

Although originally derived from the JavaScript scripting language, JSON is now a language-independent data format and code for parsing and generating JSON data is readily available in many programming languages. At Stackify, we use JSON extensively for REST APIs, serializing messages to queues, and much more.

How to improve JSON performance & usage?

11 Ways to Improve JSON Performance & Usage 1. You may need multiple JSON libraries for optimal performance and features In ASP.NET the most popular JSON library is... 2. Use streams whenever possible Most JSON parsing libraries can read straight from a stream instead of a string. This... 3. ...

Do I need to compress JSON files?

Compress your JSON Since JSON is just simple text, you can expect to get up to 90% compression. So use gzip wherever possible when communicating with your web services. 4. Avoid parsing JSON if you don’t need to This may seem obvious, but it necessarily isn’t.

Should you use JSON or XML for object serialization?

JSON isn’t the solution for everything. XML has gone out of favor as JSON has become the standard, but depending on your use case, it might still be a good fit for you, especially if you want to enforce a strong schema. Another option is BSON or MessagePack, which are types of binary-based object serialization.


1 Answers

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"
                              | # ]
like image 161
Zaid Avatar answered Nov 15 '22 08:11

Zaid