我将有一个可能非常大的JSON文件,我想从它流,而不是将它全部加载到内存中.根据以下声明(我补充说明)JSON::XS,我认为它不符合我的需要.是否有一个Perl 5 JSON模块可以从磁盘中传输结果?
在某些情况下,需要对JSON文本进行增量解析.虽然此模块始终必须同时将JSON文本和生成的Perl数据结构保留在内存中,但它允许您以递增方式解析JSON流.它通过累积文本直到它具有完整的JSON对象来实现,然后它可以解码.此过程类似于使用decode_prefix查看完整的JSON对象是否可用,但效率更高(并且可以使用最少的方法调用来实现).
为了澄清,JSON将包含一个对象数组.我想从文件中一次读取一个对象.
Cha*_*ens 12
在易用性和速度方面,JSON::SL似乎是赢家:
#!/usr/bin/perl
use strict;
use warnings;
use JSON::SL;
my $p = JSON::SL->new;
#look for everthing past the first level (i.e. everything in the array)
$p->set_jsonpointer(["/^"]);
local $/ = \5; #read only 5 bytes at a time
while (my $buf = <DATA>) {
    $p->feed($buf); #parse what you can
    #fetch anything that completed the parse and matches the JSON Pointer
    while (my $obj = $p->fetch) {
        print "$obj->{Value}{n}: $obj->{Value}{s}\n";
    }
}
__DATA__
[
    { "n": 0, "s": "zero" },
    { "n": 1, "s": "one"  },
    { "n": 2, "s": "two"  }
]
JSON::Streaming::Reader 没关系,但是速度较慢,并且接口过于冗长(尽管许多代码都不需要,但所有这些代码都是必需的):
#!/usr/bin/perl
use strict;
use warnings;
use JSON::Streaming::Reader;
my $p = JSON::Streaming::Reader->for_stream(\*DATA);
my $obj;
my $attr;
$p->process_tokens(
    start_array    => sub {}, #who cares?
    end_array      => sub {}, #who cares?
    end_property   => sub {}, #who cares?
    start_object   => sub { $obj = {}; },     #clear the current object
    start_property => sub { $attr = shift; }, #get the name of the attribute
    #add the value of the attribute to the object
    add_string     => sub { $obj->{$attr} = shift; },
    add_number     => sub { $obj->{$attr} = shift; },
    #object has finished parsing, it can be used now
    end_object     => sub { print "$obj->{n}: $obj->{s}\n"; },
);
__DATA__
[
    { "n": 0, "s": "zero" },
    { "n": 1, "s": "one"  },
    { "n": 2, "s": "two"  }
]
要解析1,000条记录,需要花费JSON::SL0.2秒和JSON::Streaming::Reader3.6秒(注意,JSON::SL一次被送入4k,我无法控制JSON :: Streaming :: Reader的缓冲区大小).
您是否看过在 search.cpan.org 上搜索“JSON Stream”时首先显示的JSON::Streaming::Reader ?
或者,通过搜索“JSON SAX”找到JSON::SL - 不是那么明显的搜索术语,但您所描述的听起来像是 XML 的 SAX 解析器。
| 归档时间: | 
 | 
| 查看次数: | 3897 次 | 
| 最近记录: |