Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^2: Converting boolean values in XMLout (code)

by ikegami (Pope)
on Jun 22, 2009 at 19:21 UTC ( #773738=note: print w/ replies, xml ) Need Help??


in reply to Re: Converting boolean values in XMLout
in thread Converting boolean values in XMLout

use strict; use warnings; use JSON::XS qw( decode_json ); use Scalar::Util qw( blessed reftype ); use XML::Simple qw( XMLout ); sub json_tree_to_xml_tree { my @to_visit = \( $_[0] ); while (@to_visit) { for my $node (${ pop @to_visit }) { if (!defined($node)) { die("Can't handle undef\n"); } elsif (JSON::XS::is_bool($node)) { # true => 1 # false => 0 $node += 0; } elsif (blessed($node)) { die("Can't handle objects\n"); } elsif (reftype($node)) { if (ref($node) eq 'ARRAY') { push @to_visit, map \$_, @$node; } elsif (ref($node) eq 'HASH') { push @to_visit, map \$_, values %$node; } else { die("Unexpected reference type\n"); } } } } } my $text = '{"a":"x","b":true}'; my $tree = decode_json($text); json_tree_to_xml_tree($tree); print XMLout($tree);

It (at least) appears a bit simpler with recursion, although it's probably a bit slower.

use strict; use warnings; use JSON::XS qw( decode_json ); use Scalar::Util qw( blessed reftype ); use XML::Simple qw( XMLout ); sub json_tree_to_xml_tree { for my $node (@_) { if (!defined($node)) { die("Can't handle undef\n"); } elsif (JSON::XS::is_bool($node)) { # true => 1 # false => 0 $node += 0; } elsif (blessed($node)) { die("Can't handle objects\n"); } elsif (reftype($node)) { if (ref($node) eq 'ARRAY') { json_tree_to_xml_tree( @$node ); } elsif (ref($node) eq 'HASH') { json_tree_to_xml_tree( values(%$node) ); } else { die("Unexpected reference type\n"); } } } } my $text = '{"a":"x","b":true}'; my $tree = decode_json($text); json_tree_to_xml_tree($tree); print XMLout($tree);


Comment on Re^2: Converting boolean values in XMLout (code)
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://773738]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (8)
As of 2014-07-25 04:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (167 votes), past polls