我正在使用Perl JSON模块将Perl哈希转换为JSON字符串.我无法弄清楚如何在保持先前分配的键和值的同时向散列数组添加新的哈希值.
我正在尝试创建以下JSON:
{
"key1":"value1",
"key2":"value2",
"arrayOfHash":[
{
"key1-1":"value1-1",
"key1-2":"value1-2"
},
{
"key2-1":"value2-1",
"key2-2":"value2-2"
}
]
}
Run Code Online (Sandbox Code Playgroud)
这是代码:
use JSON; # imports encode_json, decode_json, to_json and from_json.
$json{key1} = "value1";
$json{key2} = "value2";
%hash = ();
$hash{'key1-1'} = "value1-1";
$hash{'key1-2'} = "value1-2";
push(@{ $json{arrayOfHash} }, \%hash);
%hash = ();
$hash{'key2-1'} = "value2-1";
$hash{'key2-2'} = "value2-2";
push(@{ $json{arrayOfHash} }, \%hash);
$json = encode_json(\%json);
Run Code Online (Sandbox Code Playgroud)
我得到的是:
{
"key1":"value1",
"key2":"value2",
"arrayOfHash":[
{
"key2-1":"value2-1",
"key2-2":"value2-2"
},
{
"key2-1":"value2-1",
"key2-2":"value2-2"
}
]
}
Run Code Online (Sandbox Code Playgroud)
问题是,%hash每次引用相同的哈希 - 当你说
%hash = ();
Run Code Online (Sandbox Code Playgroud)
你没有创建一个新的哈希,你只是清空那个哈希.这有两种方法可以做你想要的.首先,您可以从一开始使用显式哈希引用:
use JSON; # imports encode_json, decode_json, to_json and from_json.
$json{key1} = "value1";
$json{key2} = "value2";
$hash = {};
$hash->{'key1-1'} = "value1-1";
$hash->{'key1-2'} = "value1-2";
push(@{ $json{arrayOfHash} }, $hash);
$hash = {};
$hash->{'key2-1'} = "value2-1";
$hash->{'key2-2'} = "value2-2";
push(@{ $json{arrayOfHash} }, $hash);
$json = encode_json(\%json);
print $json;
Run Code Online (Sandbox Code Playgroud)
其次,因为你似乎真的想尽可能避免引用,你可以使用块和my声明来做两%hash件事:
use JSON; # imports encode_json, decode_json, to_json and from_json.
$json{key1} = "value1";
$json{key2} = "value2";
{
my %hash = ();
$hash{'key1-1'} = "value1-1";
$hash{'key1-2'} = "value1-2";
push(@{ $json{arrayOfHash} }, \%hash);
}
{
my %hash = ();
$hash{'key2-1'} = "value2-1";
$hash{'key2-2'} = "value2-2";
push(@{ $json{arrayOfHash} }, \%hash);
}
$json = encode_json(\%json);
print $json;
Run Code Online (Sandbox Code Playgroud)
这些方法中的任何一种都可以满足您的需求.
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |