simtabi / json-objects
从大型JSON文件、端点或流中提取对象,同时节省内存。
dev-master / 1.0.x-dev
2024-03-07 20:44 UTC
Requires
- php: >=8.2
- psr/http-message: *
- salsify/json-streaming-parser: *
Requires (Dev)
- mockery/mockery: >=1.3
- phpunit/phpunit: >=7.0
- squizlabs/php_codesniffer: >=3.0
This package is auto-updated.
Last update: 2024-09-07 21:48:48 UTC
README
此包从大型JSON源(如文件、端点和流)提取JSON对象,同时节省内存。它通过使用 JsonStreamingParser 解析重量级的JSON,并提供了简单的API来声明要提取和处理的对象。
安装
通过Composer
composer require simtabi/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.*.key
从nested
属性中提取所有包含在key
中的对象。
在底层,JsonObjects
支持PSR-7,因此任何实现MessageInterface或StreamInterface的类都是有效的源。这使得与支持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 });
变更日志
有关最近更改的更多信息,请参阅CHANGELOG。
测试
$ composer test
贡献
有关详细信息,请参阅CONTRIBUTING和CODE_OF_CONDUCT。
安全
如果您发现任何与安全相关的问题,请通过andrea.marco.sartori@gmail.com发送电子邮件,而不是使用问题跟踪器。
鸣谢
许可
MIT许可(MIT)。有关更多信息,请参阅许可文件。