Perl YAML 到 JSON

shi*_*shu 3 perl json yaml

我想要做的应该非常简单明了。

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);
Run Code Online (Sandbox Code Playgroud)

encode_json 错误说:

cannot encode reference to scalar 'SCALAR(0x100ab630)' unless the scalar is 0 or 1
Run Code Online (Sandbox Code Playgroud)

我无法理解为什么 encode_json 认为 $yaml_hash 是对标量的引用,而实际上它是对 HASH 的引用

我究竟做错了什么?

yst*_*sth 5

它不是在抱怨 $yaml_hash,它是哈希值之一(或更深层次)中的一些参考。标量引用可以用 YAML 表示,但不能用 JSON 表示。


Mil*_*ler 5

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);
Run Code Online (Sandbox Code Playgroud)

输出:

{ bar => \17, foo => 1 }
cannot encode reference to scalar at script.pl line 18.
Run Code Online (Sandbox Code Playgroud)