在Perl中解析JSON字符串

时间:2018-12-05 15:37:38

标签: json perl parsing

我们有一台带有返回JSON字符串的API的设备。我希望能够访问JSON的特定部分,但我不知道如何使语法起作用。

use strict;
use warnings;
use CGI qw(:standard);
use LWP::Simple;
use JSON qw(decode_json);
use Data::Dumper;

my $json_request = 'http://<device ip>/API?method=Display:Input:Status:All:Get';
my $raw_json = get $(json_request)
print($raw_json) 
# Output: {"result":{"0":{"status":false},"1":{"status":false},"2":{"status":false},"3":{"status":false},"4":{"type":"unknown","status":true}},"jsonrpc":"2.0"} 

我尝试将JSON库的encode_json函数与Data :: Dumper一起使用,但这是我得到的:

print(Dumper(decode_json($raw_json)));
# Output: $VAR1 = { 'jsonrpc' => '2.0', 'result' => { '4' => { 'status' => bless( do{\(my $o = 1)}, 'JSON::PP::Boolean' ), 'type' => 'unknown' }, '1' => { 'status' => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' ) }, '3' => { 'status' => $VAR1->{'result'}{'1'}{'status'} }, '0' => { 'status' => $VAR1->{'result'}{'1'}{'status'} }, '2' => { 'status' => $VAR1->{'result'}{'1'}{'status'} } } }; 

这不仅看起来更加混乱,而且不能正确处理某些元素,而且我似乎无法访问Dumper输出或raw_json变量的元素。我当然不熟悉Perl,但是我已经尝试了所有我能想到的语法,但无法弄清楚。

我希望能够拥有一个表,该表具有从0到4行的表,根据该特定JSON元素的条目,该表只说“ true”或“ false”。例如。此处的JSON结果,

0: False
1: False
2: False
3: False
4: True

1 个答案:

答案 0 :(得分:7)

我不确定您的意思,据我所知,您的JSON包含您要提取的所有数据:

$ echo '{"result":{"0":{"status":false},"1":{"status":false},"2":{"status":false},"3":{"status":false},"4":{"type":"unknown","status":true}},"jsonrpc":"2.0"}' | json_pp 
{
   "jsonrpc" : "2.0",
   "result" : {
      "0" : {
         "status" : false
      },
      "4" : {
         "type" : "unknown",
         "status" : true
      },
      "1" : {
         "status" : false
      },
      "3" : {
         "status" : false
      },
      "2" : {
         "status" : false
      }
   }
}

也许您不了解如何正确访问它?以下代码似乎有效:

#!/usr/bin/perl
use strict;
use warnings;

use JSON qw(decode_json);

my $raw_json = '{"result":{"0":{"status":false},"1":{"status":false},"2":{"status":false},"3":{"status":false},"4":{"type":"unknown","status":true}},"jsonrpc":"2.0"}';
print "${raw_json}\n";

my $object = decode_json($raw_json)
    or die "JSON parse error\n";

my $result = $object->{result};
die "No result object found\n"
    unless $result;

foreach my $key (sort keys %{$result}) {
    print "${key}: ", $result->{$key}->{status} ? "True": "False", "\n";
}

exit 0;

输出:

{"result":{"0":{"status":false},"1":{"status":false},"2":{"status":false},"3":{"status":false},"4":{"type":"unknown","status":true}},"jsonrpc":"2.0"}
0: False
1: False
2: False
3: False
4: True