是否可以将输出的MongoDB查询解析为JSON文档?
问题描述:
首先 - 我不能使用perl MongoDB驱动程序,所以我通过IPC::Run
与MongoDB交互。现在我想从MongoDB获得输出作为散列参考。
下面是代码:是否可以将输出的MongoDB查询解析为JSON文档?
#!/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?
答
正如@Matt所示,我使用了incr_parse
方法并省略了_id
字段的输出。
[Incremental parsing](https://metacpan.org/pod/JSON::XS#INCREMENTAL-PARSING)就是你想要的,但是这些字面值的ObjectId(...)位会有问题。 –
你可以像Elasticsearch一样说出REST给mongo吗?这可能是这里的答案。 https://docs.mongodb.org/ecosystem/tools/http-interfaces/然后你可能会得到有效的JSON。 – Sobrique