如何将json解码的布尔值评估为“true”

时间:2017-05-11 10:10:08

标签: json perl boolean-expression

参考In Perl, checking a json decoded boolean value

我有一个验证子,我需要像这样检查,

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

&verify($boolean);

$boolean = 'false';
$json_string = '{"boolean_field":false}';
$decoded_json = from_json $json_string;

&verify($boolean);

sub verify {
  my $boolean = shift;
  if( $decoded_json->{'boolean_field'} eq $boolean ){
     # both are equal
  }

此if条件失败,因为$decoded_json->{'boolean_field'}返回1或0。

如何将$decoded_json->{'boolean_field'}评估为字符串'true'或'false'?

我现在的工作是

my $readBit = ($boolean =~ /false/ ) ? 0 : 1 ;
if( $decoded_json->{'boolean_field'} eq $readBit){
   # both are equal
}

2 个答案:

答案 0 :(得分:2)

如果您有布尔值,则不应使用字符串比较检查其值。你应该只问它是真还是假。您的代码看起来应该更像这样:

#!/usr/bin/perl

use strict;
use warnings;

use feature 'say';

use JSON;

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

boolean_check($decoded_json->{boolean_field});

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

boolean_check($decoded_json->{boolean_field});

sub boolean_check {
  my $value = shift;

  if ($value) {
    say 'Value is true';
  } else {
    say 'Value is false';
  }
}

如果您使用Data :: Dumper查看$decoded_json,您会看到boolean_field将包含一个对象,该对象将根据需要返回true或false值。

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

答案 1 :(得分:-1)

我们不需要使用正则表达式来查找它的真或假。
0, undef, false是假值,其余都是真的。你能试试这个解决方案吗?

use strict;
use warnings;
use JSON;

my $json_string = '{"boolean_field":0}';
# I tried with many possible combinations of boolean_field
# 0, false => returned false
# 1, 50 (Any value), true => returned true

my $decoded_json = from_json $json_string;
print 'true' if exists $decoded_json->{'boolean_field'};
# exists will check whether key boolean_field exists. It won't check for values

修改:用户只需要检查密钥,并在条件中添加exists