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



参考 在Perl中,检查一个json解码的布尔值,

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

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
}

如果条件失败,则为$decoded_json->{'boolean_field'}返回 1 或 0。

如何将$decoded_json->{'boolean_field'}评估为字符串"真"或"假"?

我现在的解决方法是

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

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

#!/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::D umper 查看$decoded_json,您将看到boolean_field将包含一个对象,该对象将根据需要返回 true 或 false 值。

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

我们不需要使用正则表达式来查找它是真的还是假的。
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

最新更新