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

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.

Replies are listed 'Best First'.
Re^6: Append JSON (from hashref)
by Anonymous Monk on Apr 06, 2017 at 15:36 UTC
    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?

        changing one line of your code to
        my $container={items=>$tmp};
        worked, providing the structure needed. Thanks

      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:  <%-{-{-{-<