I would like to iterate over a hash on the server-side, and send it over to the client in the sorted order using JSON.
My question is:
When I am in my foreach-loop and have the key and complex value (see how my hash looks like at the bottom), how do I insert it in to the JSON string?
Here is how I do that
use JSON;
my $json = JSON->new;
$json = $json->utf8;
...
# use numeric sort
foreach my $key (sort {$a <=> $b} (keys %act)) {
# somehow insert $key and contents of $act{$key} into JSON here
}
# my $json_string;
# my $data = $json->encode(%h);
# $json_string = to_json($data);
# # return JSON string
# print $cgi->header(-type => "application/json", -charset => "utf-8");
# print $json_string;
print Dumper \%act looks like this
$VAR1 = {
'127' => {
'owners' => [
'm'
],
'users' => [
'hh',
'do'
],
'date_end' => '24/05-2011',
'title' => 'dfg',
'date_begin' => '24/05-2011',
'members_groups' => [],
'type' => 'individuel'
},
'276' => {
...
And the JSON builtin sort does not enough?
see: http://metacpan.org/pod/JSON#sort_by
Sorting is supported only with JSON:PP (Perl, not XS – AFAIK)
so: