Duke Leto
Duke Leto

Reputation: 215

Perl JSON::XS non-OO interface

All of the documentation and examples I have seen for the Perl JSON::XS module use a OO interface, e.g.

print JSON::XS->new->ascii()->pretty()->canonical()->encode($in);

But I don't necessarily want all those options every time, I'd prefer to send them in a hash like you can with the basic JSON module, e.g.

print to_json($in, { canonical => 1, pretty => 1, ascii => 1 } );

sending to that encode_json yields

Too many arguments for JSON::XS::encode_json

Is there any way to do that?

Upvotes: 1

Views: 275

Answers (1)

ikegami
ikegami

Reputation: 385819

JSON's to_json uses JSON::XS if it's installed, so if you want a version of to_json that uses JSON::XS, simply use the one from JSON.

Or, you could recreate to_json.

sub to_json
   my $encoder = JSON::XS->new();
   if (@_ > 1) {
      my $opts = $_[1];
      for my $method (keys(%$opts)) {
         $encoder->$_($opts->{$_});
      }
   }

   return $encoder->encode($_[0]);
}

But doesn't help stop passing in the options every time. If you're encoding multiple data structures, it's best to create a single object and reuse it.

my $encoder = JSON::XS->new->ascii->pretty->canonical;

print $encoder->encode($in);

Upvotes: 3

Related Questions