我想要做的应该非常简单明了。
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 的引用
我究竟做错了什么?
我怀疑您的数据文件很可能包含一个由内而外的对象,并且 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)
归档时间: |
|
查看次数: |
1685 次 |
最近记录: |