Reputation: 27
Here is my code
#DATA SOURCE NAME
my $dsn = "dbi:$platform:$database:$host:$port";
#PERL DBI CONNECT
my $connect = DBI->connect($dsn, $user, $pw) || die "Connecttion Error: $DBI::errstr\n";
#PREPARE THE QUERY
my $query = qq(SELECT author, title FROM books);
my $query_handle = $connect->prepare($query);
#EXECUTE THE QUERY
$query_handle->execute();
#LOOP THROUGH RESULTS
while($row = $query_handle->fetchrow_hashref) {
push @query_output, $row;
}
#DISCONNECT FROM THE DATABASE
$connect->disconnect();
#JSON OUTPUT
print JSON::to_json(\@query_output);
and the output as below
[{"title":"Android application development for dummies /",
"author":"Felker, Donn L."},
{"title":"Beginning programming with Java for dummies /",
"author":"Burd, Barry A."}]
but i want the output to look like this
{"books":
[{"title":"Android application development for dummies /",
"author":"Felker, Donn L."},
{"title":"Beginning programming with Java for dummies /",
"author":"Burd, Barry A."}]}
to be grouped under "books", how do i do that?
Upvotes: 2
Views: 990
Reputation: 66978
Stick a reference to to @query_books
inside a hash reference:
print JSON::to_json( { books => \@query_books } );
See the Perl References Tutorial for more.
Upvotes: 4