views:

687

answers:

2

There are boolean values in the JSON data structure I am using. When call decode_json to convert it to a Perl data structure and feed to the XMLout function provided by XML::Simple, it throws an error because XMLout does not know how to deal with JSON::XS::Boolean values.

Is there a way to convert the JSON::XS::Boolean values in a data structure to XML?

my $text = '{"a":"x","b":true}'; 
my $result = decode_json($text);
my $rec = XMLout( $result, RootName => 'root', SuppressEmpty => 1);

In the code abive, I get the following error - Can't encode a value of type: JSON::XS::Boolean

A print Dumper $result gives:

$result = {
        'a' => 'x',
        'b' => bless( do{\(my $o = 1)}, 'JSON::XS::Boolean' )
      };
A: 
Leonardo Herrera
And what do you think he will get when he passes that output to XML::Simple::XMLout?
innaM
+4  A: 

I asked the same question on PerlMonks and am reproducing the proposed solution below.

Basically, the solution is to change the value of JSON::XS::Boolean to an appropriate value before passing it to XMLout:

use strict;
use warnings;

use JSON;
use XML::Simple;

my $text = '{"a":"x","b":true}';
my $result = decode_json($text);

for my $value ( values %$result ) {
    next unless 'JSON::XS::Boolean' eq ref $value;
    $value = ( $value ? 'true' : 'false' );
}

print XMLout( $result, RootName => 'root', SuppressEmpty => 1);

Output:

C:\Temp> test.pl
<root a="x" b="true" />
Bart J
Note that you do not need `each`, only `values`.
Sinan Ünür
I would change the condition to not to rely on an implementation detail. Use JSON::is_bool($scalar) instead.
Leonardo Herrera