Search code examples
jsonperlmojoliciousmojolicious-lite

Posting a JSON true value with Mojolicious


I am trying to post the following JSON with Mojo::UserAgent

use Mojo::UserAgent;

my $ua = Mojo::UserAgent->new;
my $ip = ...
$mojo->post( 'https://$ip:443/query' => json =>  { value=> True, Query => ... } );

I get an error

Bareword "JSON::true" not allowed while "strict subs"

but if I set it to True it is interpreted as a string and not a JSON true value.

Any idea how to post a JSON true value?


Solution

  • You can use Mojo::JSON::true and Mojo::JSON::false for the corresponding JSON values. You can also use the scalar references \1 for true and \0 for false if you want. A Perl undef will get converted to a JSON null.

    From the Mojo::JSON docs:

    Literal names will be translated to and from Mojo::JSON constants or a similar native Perl value.

    true  -> Mojo::JSON->true
    false -> Mojo::JSON->false
    null  -> undef
    

    In addition scalar references will be used to generate booleans, based on if their values are true or false.

    \1 -> true
    \0 -> false