PHP JSON Parser – Đọc JSON lớn từ bất kỳ nguồn nào một cách tiết kiệm bộ nhớ
JSON Parser là một pull parser không phụ thuộc vào bất kỳ thư viện nào, giúp đọc JSON lớn từ bất kỳ nguồn nào một cách tiết kiệm bộ nhớ. Bạn có thể đọc JSON từ bất kỳ nguồn nào, chẳng hạn như một chuỗi, URL, v.v., và duyệt qua nó như sau:
// a source is anything that can provide a JSON, in this case an endpoint
$source = 'https://randomuser.me/api/1.4?seed=json-parser&results=5';
foreach (new JsonParser($source) as $key => $value) {
// instead of loading the whole JSON, we keep in memory only one key and value at a time
}
Nếu bạn không muốn sử dụng `foreach`, trình phân tích này cũng đi kèm với một phương thức `traverse ` có dạng như sau:
JsonParser::parse($source)->traverse(function (mixed $value, string|int $key, JsonParser $parser) {
// lazily load one key and value at a time; we can also access the parser if needed
});
Các ví dụ trên đều mô tả việc sử dụng một URL để xử lý JSON, nhưng gói phần mềm hỗ trợ nhiều nguồn dữ liệu khác nhau. Tại thời điểm viết, tệp readme liệt kê các nguồn sau:
- strings, e.g. {“foo”:”bar”}
- iterables, i.e. arrays or instances of Traversable
- file paths, e.g. /path/to/large.json
- resources, e.g. streams
- API endpoint URLs, e.g. https://endpoint.json or any instance of Psr\Http\Message\UriInterface
- PSR-7 requests, i.e. any instance of Psr\Http\Message\RequestInterface
- PSR-7 messages, i.e. any instance of Psr\Http\Message\MessageInterface
- PSR-7 streams, i.e. any instance of Psr\Http\Message\StreamInterface
- Laravel HTTP client requests, i.e. any instance of Illuminate\Http\Client\Request
- Laravel HTTP client responses, i.e. any instance of Illuminate\Http\Client\Response
- user-defined sources, i.e. any instance of Cerbero\JsonParser\Sources\Source
Một tính năng tuyệt vời khác của thư viện này mà tôi muốn nhấn mạnh là các con trỏ (pointers), giúp trích xuất chỉ các cây con cụ thể từ một tập dữ liệu JSON lớn:
// Select the first gender result
$json = JsonParser::parse($source)->pointer('/results/0/gender');
foreach ($json as $key => $value) {
// 1st and only iteration: $key === 'gender', $value === 'female'
}
// Get all gender results
$json = JsonParser::parse($source)->pointer('/results/-/gender');
// ...
Gói phần mềm này còn nhiều tính năng khác mà tôi vẫn chưa đề cập và bạn nên kiểm tra! Ví dụ, nó có một giao diện lập trình ứng dụng (API) tiến trình để theo dõi tiến trình phân tích (tỷ lệ hoàn thành, số byte đã xử lý, v.v.). Hãy kiểm tra gói phần mềm này, lấy hướng dẫn cài đặt đầy đủ và xem mã nguồn trên GitHub!