How to send boolean value from perl script without converting them to string

I am passing a Perl data structure to encode_json

and using its return value as input for a message to the soothing API.

Example:

$data = (input1 => true);
$json_data = encode_json($data);
print $json_data; // Prints: ["input1":"true"]

$url= http://api.example.com/resources/getDataAPI
$headers = {Accept => 'application/json', Authorization => 'Basic ' . encode_base64($username . ':' . $password)};

$client = REST::Client->new();
$client->POST($url,($json_data,$headers));

      

This worked great.

Another developer has checked several input parameter validation checks recently and REST strictly accepts a boolean value without quotes.

I need to send my input as

$data = '["inout1":true]'
$client = REST::Client->new();
$client->POST($url,($data,$headers));

      

All my scripts fail as the input is JSON encoded using a function encode_json

.

I can form the JSON data manually, but the input data is sometimes very large. It is impossible to define them and change the time.

Is there any way to achieve passing the boolean value without quotes?

+3


source to share


1 answer


Use of true

and false

directly in Perl is a syntax error in the use strict

, because then not only allowed to use the words.

I am assuming you are using JSON or JSON :: XS . They use scalar references to refer to true

and false

. In particular, \1

and \0

.

$data = ( input1 => \1 );

      

Here's the relevant doc from JSON :: XS , which allows Types :: Serializer :: True and Types :: Serializer :: False:

These special values ​​from the Types :: Serialiser module become JSON true and JSON values, respectively. You can also use \1

and \0

if you like.

And a document from JSON where JSON::true

u JSON::false

can also be used:



These special values ​​become JSON true and JSON values, respectively. You can also use \1

and \0

if you like.


If you insist on using true

unquoted as in my $foo = true

, you can make subs or constants (which are indeed subs) that return \1

and \0

.

use constant false => \0;
sub true () { return \1 } # note the empty prototype

$data = ( input1 => true, input2 => false );

      

As Sinan points out in his comment , it's faster to use a constant if you don't include an empty prototype ( ()

in the subdefinition), because that way Perl can inline the call.

But in my opinion this is less clear than just using links. Always think about the next guy to work on this code.

+7


source







All Articles