Perl YAML to JSON

What I am trying to do should be VERY simple and simple.

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 errors saying:

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

      

I can't figure out why encode_json thinks $ yaml_hash is a scalar reference when in fact it is a HASH reference

What am I doing wrong?

+3


source to share


2 answers


YAML

allows you to load objects and scalar references. JSON

not default

I suspect your datafile most likely contains an "out-out" object and JSON doesn't know how to work with a scalar link.

The following demonstrates loading a YAML hash containing a scalar reference in one of the values ​​and then failing to encode it using 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);

      

Output:

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

      

+4


source


It's not the $ yaml_hash he's complaining about, it's some kind of reference in one of the hash values ​​(or deeper). Scalar links can be represented in YAML, but not in JSON.



+4


source







All Articles