【问题标题】:How to evaluate a json decoded boolean value as "true"如何将 json 解码的布尔值评估为“真”
【发布时间】:2017-10-10 06:46:24
【问题描述】:

参考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'} 评估为字符串“真”或“假”?

我现在的工作是

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

【问题讨论】:

  • 这没有任何意义。如果是1,那么就不是"true"
  • 示例 JSON 将帮助我们回答。 'false' 是一个字符串,在布尔逻辑意义上它不是“假”。我认为这就是你问题的根源。
  • @Quentin,改变了我原来的问题。两种情况都有一个验证子(真和假)
  • 如果您使用 JSON 模块或同一家族之一解码字符串,则布尔值将被转换为具有重载的对象以返回真值或假值。你只需要直接评估它。有关布尔值,请参阅 cpan 上的 JSON 文档。
  • 您引用的答案正是您所需要的。

标签: json perl boolean-expression


【解决方案1】:

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

#!/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 将包含一个对象,该对象将根据需要返回真值或假值。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我需要进入 if 块,在这两种情况下,(真假)。
    • 我不想检查密钥是否存在。我正在验证boolean_field 的值。
    • 不知道为什么你认为exists 在这里完全有用。您需要检查该值的真实性。
    • @DaveCross:在上面的评论中,他写道我需要进入 if 块,在这两种情况下(真假)。,我认为可以从exists 完成,但请纠正我。
    • 然后他说**我不想检查密钥是否存在""。我不确定问题在于他对任务的理解,还是他的英语:-)
    猜你喜欢
    • 1970-01-01
    • 2011-07-31
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    相关资源
    最近更新 更多