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

Hi, I have:
'select product, price from table'; warn Dumper $tmp; $c->render( json => $tmp) $VAR1 = [ [ 'apples', '$1' ], ['oranges', '$2' ] ];
I need the field names in the JSON like:
'select product, price from table'; warn Dumper $tmp; $c->render( json => $tmp) $VAR1 = [ [ product: 'apples', price:'$1' ], [ product: 'oranges', price: '$2' ]
How to do this with mojo?

Replies are listed 'Best First'.
Re: Mojolicios - render json with field names
by Corion (Patriarch) on Nov 10, 2016 at 08:32 UTC

    Instad of moving your data from an array to an array of hashes (AoH) afterwards, let DBI do the work:

    my $sql = 'select product, price from table'; my $results = $dbh->selectall_arrayref($sql, { Slice => {} }); warn Dumper $results;

    This will return the list as hashes just like you want to use them.

    Your syntax for JSON seems somewhat off, because JSON only accepts : for objects / hashes and not for arrays I think.

      I'm trying to use http://easyautocomplete.com/guide and need to send it JSON data like in the example. My SQL query works ok, I just don't get how to change this into a JSON return like needed in the sample data of the jQuery plugin.

        I highly doubt that you need to send the JSON in the format you described because that format is not valid JSON.

        I suggest you reconsider my approach and let DBI process the data into a format that can be directly handed to any kind of JSON processor and will produce the appropriate JSON output.

        Update:

        Note that your proposed format does not use double quotes for the entries product and price, and that your proposed format uses square brackets []. The documentation at http://easyautocomplete.com/guide does always use quoted entries and uses objects within {}.

Re: Mojolicios - render json with field names
by robby_dobby (Hermit) on Nov 10, 2016 at 06:41 UTC
    Hello AnonyMonk,

    Mojo::JSON requires perl datastructures in order to render JSON properly. What you have passed in via $tmp look like proper some JSON, so you may not need to do a lot of work but just display it directly without relying on Mojo::JSON! Do mark proper content type headers though, like Content-Type: text/json or something like that. :-)

    Oh and do read about rendering JSON on Mojolicious.