perl解析json值

时间:2012-03-28 19:16:46

标签: json perl

我在文件中有一个json输出,如下所示

{"devices":{"@size":"3","device":[{"@key":"8519","ipAddr":"172.168.2.1",
"name":"sri-asr1000"},{"@key":"1994","ipAddr":"172.17.41.5","name":
"sp-asr9k"},{"@key":"1998","ipAddr":"115.145.9.14","name":"sr-nex10k"}]}}

我希望以表格形式提取名称和IP地址。

例如

sri-asr1000 172.168.2.1
sp-asr9k 172.17.41.5
sr-nex10k 115.145.9.14

我需要perlscript,请帮助。

1 个答案:

答案 0 :(得分:4)

my $fileContents = '{"devices":{"@size":"3","device":[{"@key":"8519","ipAddr":"172.168.2.1","name":"sri-asr1000"},{"@key":"1994","ipAddr":"172.17.41.5","name":"sp-asr9k"},{"@key":"1998","ipAddr":"115.145.9.14","name":"sr-nex10k"}]}}';
use JSON;
use Data::Dumper;

my $json = JSON->new->allow_nonref();

my $hashTable = $json->decode($fileContents);
print Dumper($hashTable);

可以在http://metacpan.org/pod/JSON找到JSON库。

您的输出应该类似于

$VAR1 = { 'devices' => { '@size' => '3', 'device' => [ { '@key' => '8519', 'name' => 'sri-asr1000', 'ipAddr' => '172.168.2.1' }, { '@key' => '1994', 'name' => 'sp-asr9k', 'ipAddr' => '172.17.41.5' }, { '@key' => '1998', 'name' => 'sr-nex10k', 'ipAddr' => '115.145.9.14' } ] } };

从这一点开始,您可以轻松访问表格的每个元素并打印值。