0

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' )
      };
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
Susheel Javadi
  • 3,034
  • 3
  • 32
  • 34
  • 1
    Your question is not about JSON but it is about how to get XML::Simple to recognize the JSON boolean value and encode it in its output. You should re-write this question so it makes sense because I don't think I should go in and change the whole thing. Also, haven't you heard of single quotes in Perl? my $text = '{"a" : "x", "b": true}'; Why make it hard for others to read your code? – Sinan Ünür Jun 22 '09 at 14:59

2 Answers2

5

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" />
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
Susheel Javadi
  • 3,034
  • 3
  • 32
  • 34
0

Edit: I wrote this answer before all the edits to the original question. The question as stated now is that the original poster wants to create an XML-ready structure for using with XML::Simple; originally stated, it seemed that he just wanted to put the JSON structure in a text node.

Perl objects need to be JSON-encoded before sending them through the wire.

From your example:

my $text = '{"a":"x","b":true}'; 
my $result = decode_json($text);
print JSON->new->utf8->pretty(1)->encode($result);

You get the following:

$ perl json.pl 
{
   "a" : "x",
   "b" : true
}
Leonardo Herrera
  • 8,388
  • 5
  • 36
  • 66