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

I have a JSON serializer/deserializer object that I use (using JSON.pm and JSON::XS) and I want to convert JSON boolean values like JSON::true and JSON::false to be the javascript false instead of the javascript string "false". I'm converting blessed references with a Universal method like this(taken from the JSON docs):
use JSON -convert_blessed_universally; use constant SERIALIZER => 'JSON'; *UNIVERSAL::TO_JSON = sub { my $b_obj = B::svref_2object( $_[0] ); return $b_obj->isa('B::HV') ? { %{ $_[0] } } : $b_obj->isa('B::AV') ? [ @{ $_[0] } ] : undef ; }; sub serialize{ my $self = shift; my $params = shift; my $json_obj = JSON->new->allow_nonref; my $serialize = $json_obj->allow_blessed->convert_blessed->encode( + $params ); return $serialize; }
The question is, where/how should I change the logic so that a $hash->{'true_false_value'} = JSON::false; is turned into a javascript true_false_value: false instead of true_false_value: "false"

Replies are listed 'Best First'.
Re: JSON.pm returning "false" instead of false
by ikegami (Patriarch) on Apr 12, 2010 at 21:52 UTC

    serialize is never called. I added:

    print(serialize(undef, { key => JSON::false } ), "\n"); print(serialize(undef, bless({ key => JSON::false })), "\n");
    which prints
    {"key":false} {"key":false}

    Do you get something different?

      Well I'm using this as a serializer object inside a Mojo App......so I'm getting a database response and converting it into JSON. I have a value that is returned as $hash->{'leaf'} = JSON::false but it is returning as "leaf": "false". I'm pretty sure I'm calling the serialize function but I'll have to trace it through. This is using Mojo, which has a render_json function and I'm over-riding Mojo::JSON with a controller that does this:
      BEGIN { # install JSON and JSON::XS if you can! eval 'use JSON -convert_blessed_universally;'; eval ( $@ ? 'sub HAS_JSON(){ 0 }' : 'sub HAS_JSON(){ 1 }' ); }
      Which makes it all a bit complicated. I just noticed that the return wasn't what I expected. I'll double check that my serialize is getting called but I'm pretty sure it is.

        I'm pretty sure I'm calling the serialize function but I'll have to trace it through.

        I meant in the code you provided. In other words, you didn't demonstrate a problem since the code you posted didn't do anything at all. My guesses as to what your code might be proved to be a waste of time since I could not reproduce the problem you describe.

        Please provide minimal code that reproduces the problem. The code you posted works fine when I call it. I even tried replacing the use statement with the BEGIN block you more recently provided.