2014-09-02 72 views
3

我想要做的事情應該非常簡單直接。Perl YAML到JSON

use JSON; 
use YAML; 
use Data::Dumper; 

my $yaml_hash = YAML::LoadFile("data_file.yaml"); 
print ref($yaml_hash) # prints HASH as expected 
print Dumper($yaml_hash) # correctly prints the hash 
my $json_text = encode_json($yaml_hash); 

的encode_json錯誤出來說:

cannot encode reference to scalar 'SCALAR(0x100ab630)' unless the scalar is 0 or 1 

我無法理解爲什麼encode_json認爲$ yaml_hash是標量的參考,而實際上它是一個散列的引用

我做錯了什麼?

+2

注意,JSON是一種* YAML的子集*,如果數據僅使用JSON支持的功能,則不需要翻譯。另一方面,如果數據確實使用了YAML專用的一些功能,那麼翻譯是不可能的。 – Borodin 2014-09-02 23:59:00

回答

4

YAML使您能夠加載對象和標量引用。 JSON不默認

我懷疑你的數據文件最有可能包含一個內向外的對象,而JSON不知道如何使用標量引用。

下面演示裝載包含在值中的一個標量基準的YAML散列,然後未能使用JSON來編碼它:

use strict; 
use warnings; 

use YAML; 
use JSON; 

# Load a YAML hash containing a scalar ref as a value. 
my ($hashref) = Load(<<'END_YAML'); 
--- 
bar: !!perl/ref 
    =: 17 
foo: 1 
END_YAML 

use Data::Dump; 
dd $hashref; 

my $json_text = encode_json($hashref); 

輸出:

{ bar => \17, foo => 1 } 
cannot encode reference to scalar at script.pl line 18. 
+0

晶瑩剔透的答案!非常感謝。我的YAML確實有這樣一個標量參考。 – shikhanshu 2014-09-04 05:50:35

4

它不是$ yaml_hash它抱怨,它是一個散列值(或更深)中的某個參考。標量引用可以用YAML表示,但不能用JSON表示。

+0

希望我能+1你的答案。我沒有足夠的聲望。你是對的。 – shikhanshu 2014-09-04 05:53:06