6

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.

1

1 Answer 1

2

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.

2
  • YAML::Syck uses strings for booleans, but I think YAML::XS's behavior is probably more correct, so not a great reason to switch. See the discussion in YAML::XS, YAML::Syck and boolean values on PerlMonks. Sep 25, 2015 at 15:34
  • I'd go as far as calling the YAML::XS behaviour a bug - there is no advantage to sticking &PL_sv_no/yes directly into structures (as explained above), but they break the perl data model: no assignment or modification. I could even construct cases where this is a security bug, as an attacker who can control the YAML data could induce unexpected runtime exceptions, which is way to much action at a distance for my taste. The Types::Serialiser booleans can be detected from Perl and work like Perl scalars should, i.e. they can be printed, modified, overwritten and so on. Sep 26, 2015 at 3:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.