如何JSON编码哈希?

San*_*ing 6 perl hash json

我想迭代服务器端的哈希,并使用JSON以排序顺序将其发送到客户端.

我的问题是:

当我在我的foreach-loop中并且具有键和复杂值时(请参阅底部的哈希值),如何将其插入到JSON字符串中?

我就是这样做的

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;
Run Code Online (Sandbox Code Playgroud)

print Dumper \%act 看起来像这样

$VAR1 = {
          '127' => {
                     'owners' => [
                                   'm'
                                 ],
                     'users' => [
                                  'hh',
                                  'do'
                                ],
                     'date_end' => '24/05-2011',
                     'title' => 'dfg',
                     'date_begin' => '24/05-2011',
                     'members_groups' => [],
                     'type' => 'individuel'
                   },
          '276' => {
                     ...
Run Code Online (Sandbox Code Playgroud)

jm6*_*666 9

而JSON内置排序还不够?

请参阅:http://metacpan.org/pod/JSON#sort_by

只有JSON支持排序:PP(Perl,而不是XS - AFAIK)

所以:

use JSON::PP;
use warnings;
use strict;

my $data = {
        'aaa' => {
                a => 1,
                b => 2,
        },
        'bbb' => {
                x => 3,
        },
        'a2' => {
                z => 4,
        }
};

my $json = JSON::PP->new->allow_nonref;
#my $js = $json->encode($data); #without sort
my $js = $json->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($data);
print "$js\n";
Run Code Online (Sandbox Code Playgroud)