Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, checking a json decoded boolean value

Tags:

json

boolean

perl

Decoded JSON booleans are objects:

#!/usr/bin/env perl

use strict;
use warnings;

use Data::Dumper;
use JSON;

my $json_string = '{"boolean_field":true}';
my $decoded_json = from_json $json_string;

print Dumper $decoded_json;

Output:

$VAR1 = {
          'boolean_field' => bless( do{\(my $o = 1)}, 'JSON::XS::Boolean' )
        };

From the JSON.pm documentation I know about the following three methods:

  • JSON::is_bool
  • JSON::true
  • JSON::false

However, for some silly reason I don't know how to determine if the value of 'boolean_field' in $decoded_json is true or false.

(Sorry for the very basic question; it's been driving me batty!)

like image 355
vlee Avatar asked Jul 22 '11 15:07

vlee


People also ask

Are booleans quoted in json?

Short answer, yes that is the proper way to send the JSON. You should not be placing anything other than a string inside of quotes. As for your bool value, if you want it to convert straight into a bool, than you do not need to include the quotes.

What is json Perl?

JSON FunctionsConverts the given Perl data structure to a json string. from_json. Expects a json string and tries to parse it, returning the resulting reference. convert_blessed. Use this function with true value so that Perl can use TO_JSON method on the object's class to convert an object into JSON.


1 Answers

It will be a truthy value in Perl. Just access it as normal.

print 'true' if $decoded_json->{'boolean_field'};
like image 148
Quentin Avatar answered Oct 05 '22 17:10

Quentin