cerbero/json-objects

从大型的JSON文件、端点或流中提取对象,同时节省内存。

v1.2.0 2021-01-14 01:52 UTC

This package is auto-updated.

Last update: 2024-09-14 10:22:25 UTC


README

Author PHP Version Build Status Coverage Status Quality Score Latest Version Software License PSR-7 PSR-12 Total Downloads

此包从大型JSON源(如文件、端点和流)中提取JSON对象,同时节省内存。它通过使用JsonStreamingParser来解析大型JSON,并提供一个简单的API来声明要提取和处理的对象。

安装

通过Composer

composer require cerbero/json-objects

用法

只需传递JSON源(文件、端点或流),可选地传递包含对象的键来创建一个新的JsonObjects实例。您还可以调用工厂方法from()

$source = 'https://jsonplaceholder.typicode.com/users';

// Create a new instance specifying the JSON source to extract objects from
new JsonObjects($source);
// or
JsonObjects::from($source);

// Create a new instance specifying the JSON source and the key to extract objects from
new JsonObjects($source, 'address.geo');
// or
JsonObjects::from($source, 'address.geo');

当提供键以提取对象时,您可以使用点表示法来指示JSON的嵌套部分。例如,nested.*.keynested中每个对象的key属性中提取所有对象。

在内部,JsonObjects支持PSR-7,因此任何实现MessageInterfaceStreamInterface的接口都是有效的源。这使得与其他支持PSR-7的包(如Guzzle)的交互变得更加方便。

$response = $guzzle->get('https://jsonplaceholder.typicode.com/users');

// Create a new instance by passing an implementation of MessageInterface
JsonObjects::from($response);

// Create a new instance by passing an implementation of StreamInterface
JsonObjects::from($response->getBody());

最后,您可以决定是否逐个提取和处理对象或分块处理。内存只会分配来读取这些对象,而不是整个JSON文档。

// Extract and process one object at a time from the given JSON source
JsonObjects::from($source)->each(function (array $object) {
    // Process one object
});

// Extract and process a chunk of objects at a time from the given JSON source
JsonObjects::from($source)->chunk(100, function (array $objects) {
    // Process 100 objects
});

变更日志

请参阅变更日志以获取有关最近更改的更多信息。

测试

$ composer test

贡献

请参阅贡献指南行为准则以获取详细信息。

安全

如果您发现任何与安全相关的问题,请通过电子邮件andrea.marco.sartori@gmail.com报告,而不是使用问题跟踪器。

致谢

许可证

MIT许可证(MIT)。请参阅许可证文件以获取更多信息。