如何JSON编码哈希?

时间:2011-06-06 12:47:54

标签: perl json hash

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

我的问题是:

当我在foreach循环中并且具有键和复数值时(请参阅底部的哈希值),如何将其插入到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;

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' => {
                     ...

2 个答案:

答案 0 :(得分: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";

答案 1 :(得分:1)

Oldish post但是任何人都在寻找排序json输出..

#!/bin/perl
use warnings;
use strict;
use Sort::Naturally;
use JSON;

my $data = {
    'a10' => {
            b => 1,
            a => 2,
    },
    'bbb' => {
            x => 3,
    },
    'a2' => {
            z => 4,
    }
};
my $json = new JSON;
$json->sort_by(sub { ncmp($JSON::PP::a, $JSON::PP::b) });
my $json_text = $json->pretty->encode ($data);
print $json_text;

{
   "a2" : {
      "z" : 4
   },
   "a10" : {
      "a" : 2,
      "b" : 1
   },
   "bbb" : {
      "x" : 3
   }
}