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

In Mojolicious I have $c->render( json => 'Hello' ); which returns JSON "Hello". In CGI::Application I have return $self->json_body( {"Hello"} ); that gives {"Hello":null}. How do I get a consistent JSON response from both frameworks?

Replies are listed 'Best First'.
Re: Need same JSON response from Mojo & CGI::App (extending standard JSON)
by LanX (Saint) on Jan 04, 2017 at 14:01 UTC
    From JSON::XS (emphasis added)

    $json = $json->allow_nonref ([$enable]) $enabled = $json->get_allow_nonref
    If $enable is true (or missing), then the encode method can convert a non-reference into its corresponding string, number or null JSON value, which is an extension to RFC4627. likewise, decode will accept those JSON values instead of croaking.

    If $enable is false, then the encode method will croak if it isn't passed an arrayref or hashref, as JSON texts must either be an object or array . Likewise, decode will croak if given something that is not a JSON object or array.

    Example, encode a Perl scalar as JSON value with enabled allow_nonref, resulting in an invalid JSON text:

    JSON::XS->new->allow_nonref->encode ("Hello, World!") => "Hello, World!"
    In short, according to RFC4627 a JSON-string must start with an array (i.e. [...] ) or hash (i.e. {...} ) on top level.

    Since many applications accept more, you have the option allow_nonref to allow simple values and strings.

    As a side note: How do I post a question effectively?

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!

Re: Need same JSON response from Mojo & CGI::App
by LanX (Saint) on Jan 04, 2017 at 11:12 UTC
    Please try to pass the same data structure to both, if you want the same result.

    The first one is a string, the second a (malformed) hash.

    I'd say { Hello => 1} does the same.

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!

      With that I get hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this) returned
        You haven't told us which result you need on the receiving side.

        Only "hello" ?

        Since JSON is an (JS) Object Notation I'm not sure if blank strings (i.e. nonref) are legal.

        Cheers Rolf
        (addicted to the Perl Programming Language and ☆☆☆☆ :)
        Je suis Charlie!

        my mistake, I get the following {"Hello":1}