nleaman has asked for the wisdom of the Perl Monks concerning the following question:

#!/usr/bin/perl -w use strict; use Data::Dumper; use JSON; # sample json data my $json_text = <<END; { "id": 559, "bool_one": false, "bool_two": false, "bool_three": false, "alertStates": ["OK"] } END my $json_text_decoded = decode_json $json_text; print Dumper $json_text_decoded ; print "\n$json_text_decoded\n"; foreach (keys %{($json_text_decoded)}) { print " $_ = $$json_text_decoded{$_}\n"; }
OUTPUT:
$VAR1 = { 'alertStates' => [ 'OK' ], 'bool_two' => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' ) +, 'bool_three' => $VAR1->{'bool_two'}, 'bool_one' => $VAR1->{'bool_two'}, 'id' => 559 }; HASH(0x100873888) alertStates = ARRAY(0x1008739c0) bool_two = false bool_three = false bool_one = false id = 559

Replies are listed 'Best First'.
Re: Why is Dumper showing decoded JSON booleans like this?
by ikegami (Patriarch) on Mar 03, 2010 at 18:08 UTC
    Perl doesn't have a boolean type. In order to be able to do round trips, JSON uses an overloaded object to represent booleans.
      Okay. That makes sense. I guess my problem then becomes something different which is when using PHP::Serialization to serialize the decoded json text:
      #!/usr/bin/perl -w use strict; use Data::Dumper; use JSON; use PHP::Serialization qw(serialize unserialize); my $json_text ='{ "boolean": true }'; my $json_text_decoded = decode_json $json_text; serialize($json_text_decoded);

      OUTPUT:

      Not a HASH reference at lib/PHP/Serialization.pm line 454.

      It dies when working on the object data type. Is there a straightforward way to convert the boolean object to a literal string?

        You'll have to traverse the returned data structure, using JSON::is_bool to check for boolean nodes, replacing boolean nodes with the values of your choice.

        If PHP::Serialization supported custom object serializers, you could just write one of those for JSON::PP::Boolean, but it doesn't appear to be the case.

Re: Why is Dumper showing decoded JSON booleans like this?
by Anonymous Monk on Mar 03, 2010 at 18:11 UTC
    Because that is what they are , and its Dumpers job?
    BEGIN { package WhatItDoes; sub new { bless {}, shift } } use Data::Dumper; use CGI; print Dumper( { 6, CGI->new(''), 1 , WhatItDoes->new }); __END__ $VAR1 = { '6' => bless( { '.parameters' => [], 'use_tempfile' => 1, '.charset' => 'ISO-8859-1', '.fieldnames' => {}, 'param' => {}, 'escape' => 1 }, 'CGI' ), '1' => bless( {}, 'WhatItDoes' ) };