首先 - 我不能使用perl MongoDB驱动程序,因此我通过IPC::Run
与MongoDB进行交互。现在我想把MongoDB的输出作为散列引用。
这是代码:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON::XS;
use Try::Tiny;
use IPC::Run 'run';
use Data::Dumper;
my @cmd = ('/opt/mongo/bin/mongo', '127.0.0.1:27117/service_discovery', '--quiet', '-u', 'test', '-p', 'test', '--eval', 'db.sit.find().forEach(function(x){printjson(x)})');
my $out;
run \@cmd, '>>', \$out;
my $coder = JSON::XS->new->ascii->pretty->allow_nonref;
my $dec = try {my $output = $coder->decode($out)} catch {undef};
print Dumper (\%$dec);
现在无效,%$dec
为空
以下是MongoDB查询的输出(值$out
):
{
"_id" : ObjectId("5696787eb8e5e87534777c82"),
"hostname" : "lab7n1",
"services" : [
{
"port" : 9000,
"name" : "ss-rest"
},
{
"port" : 9001,
"name" : "ss-rest"
},
{
"port" : 8060,
"name" : "websockets"
},
{
"port" : 8061,
"name" : "websockets"
}
]
}
{
"_id" : ObjectId("56967ab2b8e5e87534777c83"),
"hostname" : "lab7n2",
"services" : [
{
"port" : 8030,
"name" : "cloud-rest for batch"
},
{
"port" : 8031,
"name" : "cloud-rest for batch"
},
{
"port" : 8010,
"name" : "cloud-rest for bespoke"
},
{
"port" : 8011,
"name" : "cloud-rest for bespoke"
}
]
}
如何让解析器将此输出视为合法的JSON?
答案 0 :(得分:0)
根据@Matt的建议,我使用了incr_parse
方法并在输出中省略了_id
字段。