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

I create JSON from a DB query like this for use with a javascript autocomplete tool
my $tmp = $dbh->selectall_arrayref($query, { Slice => {} }, $SearchWor +d ); my $json_str = encode_json( $tmp );
This works, but I want to add to the JSON response before returning it to ensure Asynchronous responses (http://easyautocomplete.com/guide#sec-async). How can I add the inputphrase to existing JSON object before returning it? inputPhrase in the easyautocomplete docs would have the value stored in $SearchWord in my perl.

Replies are listed 'Best First'.
Re: Append JSON (from hashref)
by Corion (Patriarch) on Apr 06, 2017 at 11:11 UTC

    Don't add it to the JSON, add it to $tmp.

    Alternatively, consider selecting the information directly from the database.

      So the existing JSON looks like
      [{"DESCRIPTION":"Description of record","RECNO":"RECORDNumber"}, ... m +ore records here ...]
      the database query is
      SELECT RECNO, DESCRIPTION FROM RECORDS_TABLE WHERE RECNO LIKE ?
      Called with
      $dbh->selectall_arrayref($query, { Slice => {} }, $SearchWord );
      Is there a way I can change the query to return a structure required by this plugin, while including the additional field
      "inputPhrase": $SearchWord

        Yes.

        See perldsc on how to manipulate Perl data structures.

        You could either add your entry to the result directly, in your Perl code:

        $tmp->[0]->{ 'inputPhrase' } = $SearchWord;

        ... or simply select the search phrase as another column:

        SELECT RECNO, DESCRIPTION, ? as inputPhrase FROM RECORDS_TABLE WHERE RECNO LIKE ?
        ... $sth->execute( $SearchWord, $recno ); ...

        like Corion said, add it to $tmp

        $tmp->{inputPhrase}=$SearchWord;
        Then it will be converted to json just fine.

        Edit: Now im not paying enough attention, The hash is inside an array at $tmp->[0] See Re^3: Append JSON (from hashref)