2016-12-08 7 views
1

嘗試轉換JSONYAML。有這樣的代碼正確和簡單的方法將JSON :: PP :: Boolean轉換爲0,1與perl

#!/usr/bin/env perl 

use 5.014; 
use warnings; 

use JSON; 
use YAML; 

my $json_string = q(
{ 
    "some" : [ 
     { "isFlagged" : true, "name" : "Some name" }, 
     { "isFlagged" : false, "name" : "Some other name" } 
    ] 
} 
); 

my $data = decode_json($json_string); 
say Dump($data); 

它產生:

--- 
some: 
    - isFlagged: !!perl/scalar:JSON::PP::Boolean 1 
    name: Some name 
    - isFlagged: !!perl/scalar:JSON::PP::Boolean 0 
    name: Some other name 

我需要JSON::PP::Boolean對象轉換爲01。當然,我可以從YAML輸出中刪除每個!!perl/scalar:JSON::PP::Boolean字符串,但這在我看來並不是一個正確的解決方案。

那麼,什麼是最簡單的和正確的方式轉換所有JSON::PP::Boolean對象簡單01,所以YAML將產生

--- 
some: 
    - isFlagged: 1 
    name: Some name 
    - isFlagged: 0 
    name: Some other name 

回答

5

使用YAML的Stringify option

{ 
    local $YAML::Stringify = 1; 
    say Dump($data); 
} 

這使得YAML使用JSON :: PP :: Boolean代替轉儲對象內部的字符串重載。

+1

謝謝你救了我表演上'遞歸散步的麻煩$ data'用'JSON :: is_bool' – Zaid

+0

是來按摩吧! :)它確實是我想要的。非常感謝。 – cajwine

1

的一般解:

use Carp qw(carp); 

sub convert_bools { 
    my %unrecognized; 

    local *_convert_bools = sub { 
     my $ref_type = ref($_[0]); 
     if (!$ref_type) { 
      # Nothing. 
     } 
     elsif ($ref_type eq 'HASH') { 
      _convert_bools($_) for values(%{ $_[0] }); 
     } 
     elsif ($ref_type eq 'ARRAY') { 
      _convert_bools($_) for @{ $_[0] }; 
     } 
     elsif (
       $ref_type eq 'JSON::PP::Boolean'   # JSON::PP 
      || $ref_type eq 'Types::Serialiser::Boolean' # JSON::XS 
     ) { 
      $_[0] = $_[0] ? 1 : 0; 
     } 
     else { 
      ++$unrecognized{$ref_type}; 
     } 
    }; 

    &_convert_bools; 

    carp("Encountered an object of unrecognized type $_") 
     for sort values(%unrecognized); 
} 

my $data = decode_json($json); 
convert_bools($data); 
+0

爲什麼不使用'JSON :: is_bool'? – Zaid

+0

@Zaid,如果你使用JSON.pm,我想這很好。但是,我從來沒有使用該模塊 - 它的默認方式是JSON :: PP而不是JSON :: XS太容易出錯 - 我不想將我的解決方案限制爲僅與某些版本的某些JSON一起工作模塊。 – ikegami

+0

例如,'JSON :: is_bool'在使用JSON :: PP和JSON :: XS的項目中不起作用。 – ikegami

相關問題