in reply to Re^3: Append JSON (from hashref)
in thread Append JSON (from hashref)

Thanks, but this first solution means inputPhrase is added in with the details of the first result
[{"DESCRIPTION":"Description of record","RECNO":"RECORDNumber", "input +Phrase":"RECORDNumber}, ... more records here
and not outside of the list of results like in the json linked above (won't let me post with the URL here)

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

    Ah, if you want a different structure, just create that structure.

    Consider writing your data structure in Perl - Perl looks very much like JSON, except that : is spelled => in Perl.

      Can you give some advice on preping this in perl, so far my attempt is failing to produce a structure required:
      while (my $row = $sth->fetchrow_hashref) { print "doc_no: $row->{RECNO} DESCRIPTION: $row->{DESCRIPTION}\n"; $hash{$int} = '"RECNO": "' . $row->{RECNO} . '","DESCRIPTION": "' . +$row->{DESCRIPTION} .'"'; $int ++; } # figure out how to add inputPhrase later.
      Is there a structure I can use which means I don't have to have the $int part?

        If you want to numerically index something, use an array, not a hash.

        See perldsc on Perl Data Structures, and maybe Modern Perl about a good book on Perl in general.

        There is something you are not telling us, your example link shows a hash as the containing structure, yet your example json is a hash inside an array. Is this what you want?

        my $tmp = $dbh->selectall_arrayref($query, { Slice => {} }, $SearchWor +d ); my $container={items=>$tmp->[0]}; $container->{inputPhrase}=$SearchWord; my $json_str = encode_json( $container );
        Just what is it you expect to see returned?

        This is tangential to the main theme of this thread, but a statement like
            $hash{$int} = '"RECNO": "' . $row->{RECNO} . '","DESCRIPTION": "' . $row->{DESCRIPTION} .'"';
        can be written in what I consider a much more readable way as, e.g.,
            $hash{$int} = qq{"RECNO": "$row->{RECNO}","DESCRIPTION": "$row->{DESCRIPTION}"};
        using the  qq{} generic double-quotish (i.e., interpolating) string constructor (see Quote and Quote-like Operators in perlop). Note that bracketing delimiters handle balanced nested bracketing delimiters of the same type, so something like
            $hash{$int} = qq{{... whatever ...}};
        works as you expect.


        Give a man a fish:  <%-{-{-{-<