Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve boolean type from YAML document in Perl 5?

I have a YAML document that contains boolean values:

---
ok: false

I want to load it in Perl 5 and preserve the 'boolean' type to be able later to serialize the document properly to JSON using true/false values, not ""/"1".

The following converter I wrote fails to preserve booleans:

#!/usr/bin/env perl

use strict;
use warnings;

use YAML::XS qw<LoadFile>;
use JSON::MaybeXS ();

print JSON::MaybeXS->new->ascii->pretty->canonical->encode(LoadFile shift)

Here is the (corrupted) output:

{
   "fine" : ""
}

I hope some hooks exist in some YAML loader to map true/false to JSON::true/JSON::false or $Types::Serialiser::true/$Types::Serialiser::false.

like image 827
dolmen Avatar asked Sep 24 '15 14:09

dolmen


1 Answers

If such a YAML module exists, it has to be a pretty obscure one. The one you use here, YAML::XS simply translates boolean values in YAML data to the standard internal values PL_sv_yes and PL_sv_no, and those are (as far as I can see) impossible to recognize as special.

On the positive side, it seems pretty straightforward to patch YAML::XS to use Types::Serialiser for booleans and send in a pull request.

like image 69
Calle Dybedahl Avatar answered Nov 09 '22 20:11

Calle Dybedahl