【发布时间】:2011-09-09 06:47:22
【问题描述】:
我想在服务器端迭代哈希,并使用 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;
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' => {
...
【问题讨论】:
-
听起来您正在尝试使用特定顺序的键生成 JSON 对象。 JSON 规范明确指出对象是无序的,因此无法保证您会以相同的顺序将它们从 JSON 中取出……这使得练习看起来毫无意义。
-
@Quentin:我不知道。谢谢。如何按我指定的顺序发送散列中的数据?
-
你不能。如果顺序很重要,请使用数组而不是哈希。 (虽然它可以是一个 hashrefs 数组)。