Mose
Mose

Reputation: 563

jqgrid via Perl

I'm trying to send JSON information to jqgrid via Perl, however I'm struggling on how to get the appropriate JSON structure:

Per JQgrid docs, the JSON needs to be in the following format:

{
"total": "xxx",
"page": "yyy",
"records": "zzz",
"rows" : [
{"id" :"1", "cell" :["cell11", "cell12", "cell13"]},
{"id" :"2", "cell":["cell21", "cell22", "cell23"]},
...
]
}
#!/usr/bin/perl 
use CGI (-debug);
use DBI;
use JSON;
use POSIX qw(ceil);
use strict;
use warnings;
...
my $i=0;
my $response = {};
$response->{total} = $total_pages;
$response->{page} = $page;
$response->{records} = $count;
while ( my $row = $sth->fetchrow_hashref ){
        $response->{rows}->[$i]->{id} = $i;
        $response->{rows}->[$i]->{cell} = ($row);
        $i++;
}
print $cgi->header(-type => "application/json", -charset => "utf-8");
print JSON::to_json($response);

I'm pretty sure I need a hash of arrays, but I can't seem to figure out how to go about it.

Upvotes: 0

Views: 625

Answers (1)

DavidO
DavidO

Reputation: 13942

This is one problem:

$response->{rows}->[id]

In that phrase you're taking a hashref ($response), accessing its hash key "rows", and then accessing an anonymous array referred to by $response->{rows}. So far so good, but the anonymous array cannot have an element named 'id', unless 'id' is defined somewhere as a constant, which I don't see anywhere in the code you posted. It's more likely that you mean "$response->{rows}{id}". In other words, a hash of hashes. Note, the -> operator is redundant when sandwiched between indices, so I removed it.

However, you mentioned in your post that you need a hash of arrays. But that would have to look more like $response->{rows}[0].

One thing I find useful sometimes is to just use Data::Dumper to dump the return value of fetchrow_hashref to see what it looks like. You may already have a picture of it in your mind, but sometimes seeing it dumped out as a datastructure will help you to better visualize how your datastructure should be rearranged to fit the design requirements.

Upvotes: 1

Related Questions